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
//callback function
if($wpdb->get_var(“SHOW TABLES LIKE ‘$table_name'”)!=$table_name){
    $sql=“CREATE TABLE $table_name (
      name tinytext NOT NULL
    //reference to upgrade.php file
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_.



Leave a Reply

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

You are commenting using your 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