How to create custom table from plugin in WordPress 3


When creating plugin, we need to create a custom table. We will use register hook activation, de-activation and uninstall to handle database creation and removal. Now, we start with database created automatically when plugin installed / activated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* Register installation into hook */
register_activation_hook(__FILE__, ‘your_plugin_install’);

/* Install montage SQL into database */
function your_plugin_install() {
    global $wpdb;
    $table_name = $wpdb->prefix.’your-table’;

    $sql = "CREATE TABLE IF NOT EXISTS ". $table_name . " (
            id int(11) NOT NULL AUTO_INCREMENT,
            name varchar(255) binary DEFAULT NULL,
            PRIMARY KEY (id)
            ) TYPE=MyISAM AUTO_INCREMENT=1;
    ";

    require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);
    dbDelta($sql);
}


When you activate the plugin, it will create table which contain “id” and “name” coloumn.

Now, we need to remove table if plugin de-activate or uninstalled. So, we should use de-activate / uninstall register hook :

1
2
3
4
5
6
7
8
9
10
11
12
13
/* Register uninstall hook function executed if plugin uninstalled */
register_deactivation_hook(__FILE__, ‘your_plugin_uninstall’);

/* Register uninstall hook function executed if plugin uninstalled */
register_uninstall_hook(__FILE__, ‘your_plugin_uninstall’);

/* Delete table */
function your_plugin_uninstall() {
    global $wpdb;
    $table_name = $wpdb->prefix . ‘your-table’;

    $wpdb->query("DROP TABLE IF EXISTS $table_name ");
}

It easy to create / remove table from plugin in WordPress 3 😀


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.