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?


1 Answer 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');

        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) {
add_action('plugins_loaded', 'myplugin_update_db_check');
  • Does it make any difference if the db version is stored as a constant instead of a global variable?
    – urok93
    Aug 13, 2012 at 12:13
  • There is no difference, but you need to make sure your constant is unique (avoid conflicts) Oct 11, 2017 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.