Created
March 21, 2012 18:56
-
-
Save kurtpayne/2151282 to your computer and use it in GitHub Desktop.
Test dbDelta
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment