wordpress在开发插件过程有时候需要创建自定义的数据表,实现方法很简单,将以下代码放于你的插件文件中即可:
<?php function plugin_name_activation() { require_once( ABSPATH . '/wp-admin/includes/upgrade.php' ); global $wpdb; $db_table_name = $wpdb->prefix . 'table_name'; if( $wpdb->get_var( "SHOW TABLES LIKE '$db_table_name'" ) != $db_table_name ) { if ( ! empty( $wpdb->charset ) ) $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset"; if ( ! empty( $wpdb->collate ) ) $charset_collate .= " COLLATE $wpdb->collate"; $sql = "CREATE TABLE " . $db_table_name . " ( `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, `type` varchar(100) NOT NULL DEFAULT '', `extra` longtext NOT NULL, `date_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) $charset_collate;"; dbDelta( $sql ); } } register_activation_hook(__FILE__, 'plugin_name_activation'); ?>
插件卸载时删除表代码:
function pluginUninstall() { global $wpdb; $table = $wpdb->prefix."your_table_name"; //Delete any options thats stored also? //delete_option('wp_yourplugin_version'); $wpdb->query("DROP TABLE IF EXISTS $table"); } register_deactivation_hook( __FILE__, 'pluginUninstall' );