Home > Net >  Plugin attempts to create database each time the plugin is activated
Plugin attempts to create database each time the plugin is activated

Time:09-10

Does anyone know how I can do this within this section of the code?

Check the database version of the plugin and compare it to the current version installed. If the version that's installed is newer than what's in the database, run install scripts.

global $rhit_version;
$rhit_version = '0.1.0';

function rhit_install() {
    global $wpdb, $rhit_version;

    $table_name = $wpdb->prefix . 'views';
    $charset_collate = $wpdb->get_charset_collate();
    $sql = <<<SQL
    CREATE TABLE $table_name (
        `id` int(9) UNSIGNED NOT NULL AUTO_INCREMENT,
        `user_id` bigint(20) UNSIGNED NOT NULL,
        PRIMARY KEY (`id`)
    ) $charset_collate;
    SQL;

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );

    add_option( 'rhit_db_version', $rhit_version );
}

CodePudding user response:

You should check both versions, if plugin version is highest, then you run your code... Else, just return the function.

global $rhit_version;
$rhit_version = '0.1.0';

function rhit_install() {
    $db_version = '0.0.1' // some how you get the version from DB

    // Check both versions
    if ( $rhit_version <= $db_version )
        return;

    /** Else, run your code */
}
  • Related