Run function on plugin upgrade

Hi a new version of a plugin I have in the repository changes the way the data is stored in the database, how can I perform a check on upgrade that automatically moves the data to the new location, so the users don’t lose any of their settings and are not aware of what is happening beneath the hood?

Related posts

Leave a Reply

1 comment

  1. global $myplugin_db_version;
    $myplugin_db_version = "1.0";
    
    function myplugin_install() {
        global $wpdb;
        global $myplugin_db_version;
    
        $table_name = $wpdb->prefix . "myplugin";
    
        $installed_ver = get_option( "myplugin_db_version" );
    
        if( $installed_ver != $myplugin_db_version ) {
    
            $sql = "CREATE TABLE $table_name (
                    id mediumint(9) NOT NULL AUTO_INCREMENT,
                    time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
                    name tinytext NOT NULL,
                    text text NOT NULL,
                    url VARCHAR(100) DEFAULT '' NOT NULL,
                    UNIQUE KEY id (id));
            ";         
    
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
    
            update_option( "myplugin_db_version", $myplugin_db_version );
    
        }
    }
    
    function myplugin_update_db_check() {
        global $myplugin_db_version;
        if ( get_site_option( 'myplugin_db_version' ) != $myplugin_db_version) {
            myplugin_install();
        }
    }
    add_action('plugins_loaded', 'myplugin_update_db_check');