Add Custom Database Tables to New Sites in WP 3.0 Multisite

Developers appreciate that you may need to associate an additional table with a new blog in WordPress multi-site. All it takes is one function and an action.

I am currently working on a personal project using the multisite capabilities of the alpha version of WordPress 3.0. When a new site is added to the WordPress network, a slew of new tables are added to the database, prefixed with the defined table prefix and the blog ID (eg: wp_2_).

Note: This article is about a development version of WordPress (3.0 alpha). Although the techniques presented here are likely to be valid in the publicly released version, please test this on a development site first.

For this project, I needed each new site to automatically have an additional table created that would hold information for the plugin I’m working on. The key is to tap into the wpmu_new_blog action, which fires directly after a new site is created.

The wpmu_new_blog action runs at the end of wpmu_create_blog(), a function located in /wp-includes/ms-functions.php which creates the new site. The action is passed two variables: $blog_id, which is the ID of the newly created site, and $user_id, which is the ID of the administrator of the site.

Here’s my finished code:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
function nt_installTables($blog_id){
    global $wpdb;
    $table_name = $wpdb->get_blog_prefix($blog_id) . 'mytable';
        $sql = "CREATE TABLE ". $table_name ."  (
                    ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                    table_id varchar(20) NOT NULL,
                    page_id text NOT NULL,
                    html text NOT NULL,
                    snippet bigint(20) NOT NULL,
                    UNIQUE KEY ID (ID)) CHARSET=utf8;
                    ";
        require_once ABSPATH . '/wp-admin/includes/upgrade.php';
        dbDelta($sql); //do it
}
add_action('wpmu_new_blog', 'nt_installTables');

Don’t forget you can also pass $user_id to your function.

%d bloggers like this: