0

I am creating a plugin, that supposed to work on WP multisite yesterday. I've installed WP multisite on my server. While testing I found out that register_activation_hook created 1 table on the main blog only, while I have 2 more blogs.

Here is how I create the tables now:

global $wpdb;
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$table_name = $wpdb->prefix . "pm_services";
$table = "CREATE TABLE $table_name (
  ID bigint(20) NOT NULL AUTO_INCREMENT,
  service_id bigint(20) NOT NULL,
  name varchar(200) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  UNIQUE KEY cuunique (`ID`)
  );";
dbDelta($table);

Is there a way to creating this table for every blog on the network upon activation ?

1 Answer 1

4

The basic process - on activation, check if is_multisite, get all of the sites with wp_get_sites, loop over the results with foreach and switch_to_blog for each site ID, and create the table.

You'll also need to hook the wpmu_new_blog action, check if is_plugin_active_for_network, switch to that blog ID and run your activation code, so sites added after activation have their table created. Don't forget to switch back to the original blog ID after you run your activation.

4
  • Thanks for the answer. so, basically in register_activation_hook i'll check for multi site, and run through the blogs and create one for each, but what did you mean about wpmu_new blog ?
    – Neta Meta
    Commented Jan 17, 2014 at 18:33
  • After your plugin is activated, new blogs can be created, so your activation code has to run or those new blogs won't have their own table.
    – Milo
    Commented Jan 17, 2014 at 18:35
  • yea make sense.. so the table that was created for the network is available for everyone ? i mean right now on my db i see the tables i create without blog number prefix.. if they are accessible to the whole network, how do i access them ? to what blog do i switch ?
    – Neta Meta
    Commented Jan 17, 2014 at 18:38
  • 1
    no, that table is just for the main site. additional sites have table prefixes starting at 2. The main site is typically 1, but the main site tables don't have that prefix, as you can create a network on top of an existing single install.
    – Milo
    Commented Jan 17, 2014 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.