public
Last active

Test dbDelta

  • Download Gist
my-plugin.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
<?php
/*
Plugin Name: My Plugin
Description: Test dbDelta
Version: 0.1
*/
 
// Upgrade when the admin loads
add_action( 'admin_init', 'myplugin_upgrade' );
 
// Activation & Deactivation hooks
register_activation_hook( __FILE__, 'myplugin_activate' );
register_deactivation_hook( __FILE__, 'myplugin_deactivate' );
 
/**
* Activate the plugin, install version 0.1 of the table
*/
function myplugin_activate() {
global $wpdb;
$table_name = $wpdb->prefix . 'myplugin_table';
$sql = "CREATE TABLE $table_name (
id bigint(11) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
`text` VARCHAR(255) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
update_option( 'myplugin_version', '0.1' );
}
 
/**
* Deactivate the plugin, drop the table
*/
function myplugin_deactivate() {
global $wpdb;
$table_name = $wpdb->prefix . 'myplugin_table';
$sql = "DROP TABLE IF EXISTS $table_name;";
$wpdb->query( $sql );
delete_option( 'myplugin_version' );
}
 
/**
* Upgrade database to version 0.1.1
*/
function myplugin_upgrade() {
global $wpdb;
$table_name = $wpdb->prefix . 'myplugin_table';
$version = get_option( 'myplugin_version' );
if ( empty( $version ) || version_compare( $version, '0.1.1' ) < 0 ) {
$sql = "CREATE TABLE $table_name (
id bigint(11) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
`text` VARCHAR(255) DEFAULT '' NOT NULL,
`user_ip` int(11) DEFAULT 0,
UNIQUE KEY `id` (`id`),
KEY `user_ip` (`user_ip`)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
update_option( 'myplugin_version', '0.1.1' );
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.