WordPress multisite programming tricks

This pulls together some notes on handling plugin programming for WordPress multisite (network) installations.

Basic information

Lots of this information comes from the globally instantiated $wpdb object.

is_multisite()        // true if a multisite instance
is_main_site()        // true if the main site, or a non-multisite instance
get_current_blog_id() // integer id of the current "blog" 1=main, 2,3,...
get_network_id()      // 1 as of v5.8
global $wpdb;
$wpdb->prefix       // tablename prefix ... wp_. wp_2_, wp_3_ for multisite
$wpdb->base_prefix  // tablename prefix ... wp_ 

Tables

To get a list of WordPress tables you can use the wpdb::tables() method. Here’s a quick way to get a useful list of tables. This list include the global tables (wp_users, wp_usermeta, etc) for the main or only site, and the site-specific tables (wp_posts, etc) for the current site.

$wpTables = array_flip( $wpdb->tables( 'blog', true ) );
if (is_main_site()) {
  $wpTables = $wpTables + array_flip( $wpdb->tables( 'global', true ) );
}

This list also includes tables for some active plugins that register their tables with the wpdb class. WooCommerce registers its plugins. Many other plugins don’t.

Leave a Comment