Create Database Tables When Plugin is Activated in WordPress

Googled web, all articles suggested to use register_activation_hook, it does not work for me. For instance, this article “Create Database Tables When Plugin is Activated“. It gave out a complete solution as following:

$your_db_name = $wpdb->prefix . 'your_db_name';
 
// function to create the DB / Options / Defaults					
function your_plugin_options_install() {
   	global $wpdb;
  	global $your_db_name;
 
	// create the ECPT metabox database table
	if($wpdb->get_var("show tables like '$your_db_name'") != $your_db_name) 
	{
		$sql = "CREATE TABLE " . $your_db_name . " (
		`id` mediumint(9) NOT NULL AUTO_INCREMENT,
		`field_1` mediumtext NOT NULL,
		`field_2` tinytext NOT NULL,
		`field_3` tinytext NOT NULL,
		`field_4` tinytext NOT NULL,
		UNIQUE KEY id (id)
		);";
 
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
	}
 
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'your_plugin_options_install');

However, tried many times with no luck. Finally, use add_action hook and got success.

function my_plugin_install() {
   global $wpdb, $table_name;
   $charset_collate = $wpdb->get_charset_collate();

   if($wpdb->get_var("show tables like '$table_name'") != $table_name)  {
	    $sql = "CREATE TABLE wp_moove_activity_log (
            id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            post_id bigint(20) UNSIGNED NOT NULL,
            user_id int(11) DEFAULT NULL,
            status tinytext,
            user_ip tinytext,
            city tinytext,
            country varchar(255) NOT NULL,
            post_type tinytext,
            referer tinytext,
            campaign_id tinytext,
            month_year tinytext,
            display_name tinytext,
            visit_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY id (id)
        ) $charset_collate;
        CREATE TABLE wp_sql (id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
            post_id int(11) NOT NULL,
            `sql` varchar(4000) NOT NULL,
            `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY id (id)
        ) $charset_collate;";

 	require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	dbDelta($sql);
    }
}
add_action( 'plugins_loaded', 'my_plugin_install' );

Related hooks

register_activation_hook ($file, $function) to be run when the plugin is activated
register_deactivation_hook ($file, $function) is called once any activated plugins have been loaded
add_action('plugins_loaded', 'my_plugin_install') Fires once activated plugins have loaded
register_uninstall_hook('uninstall.php', 'on_uninstall') function on_uninstall in the uninstall.php when the plugin will be deleted

Reference: How to Create Custom Database Tables for WordPress Plugins

Leave a Reply