How To Create Database Table When WordPress Plugin is Activated

This post is for plugin developers. Sometimes wordpress plugin developers need to create a table in database when the plugin is activated. For this purpose, we need to use register_activation_hook. Using this hook, we can execute a callback function when the plugin is activated.

Inside the callback function, we write the code to check if the needed table is already created. If not we create a new table. To create a new table for the plugin, we will not write direct mysql_connect code. Instead we use dbDelta function which is a part of wordpress assigned to execute sql commands. To use this function, we need to include wp-admin/includes/upgrade.php explicitly.

If callback_plugin() is the callback function for register_activation_hook, here is a sample code to create table in wordpress using php code.

//action hook for plugin activation
register_activation_hook(__FILE__,‘callback_plugin’);
//callback function
functioncallback_plugin(){
global$wpdb;
$table_name=$wpdb->prefix.“your-table-name”;
if($wpdb->get_var(“SHOW TABLES LIKE ‘$table_name'”)!=$table_name){
    $sql=“CREATE TABLE $table_name (
      id int NOT NULL AUTO_INCREMENT,
      name tinytext NOT NULL
    );”;
    //reference to upgrade.php file
    require_once(ABSPATH.‘wp-admin/includes/upgrade.php’);
    dbDelta($sql);
}
}
The global $wpdb variable is an object of wpdb class in wordpress. It handles all database related operations. ABSPATH is a defined variable in wordpress which points to root path of wordpress installation. $wpdb->prefix gets the table prefix defined by admin in wp-config.php file. By default it will be wp_.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s