One of WordPress's many strengths is the ability to create and manage multiple websites from a single installation. In these situations, each site has its own set of tables in the MySQL database. Therefore, when preparing a plugin that creates custom tables and may be used in network installations, extra code must be put in place to create the new tables under each site's structure.
The first changes are done in the ch8bt_activation function, where we check whether we are dealing with a multisite installation. If that is the case, we will cycle through each existing site and make a call to create the new table, as we saw in the main recipe code:
function ch8bt_activation() {
// Get access to global database access class
global $wpdb;
// Check to see if WordPress installation is a network
if ( is_multisite() ) {
// If it is, cycle through all blogs, switch to them
// and call function to create plugin table
if ( !empty( $_GET['networkwide'] ) ) {
$start_blog = $wpdb->blogid;
$blog_list =
$wpdb->get_col( 'SELECT blog_id FROM ' . $wpdb->blogs );
foreach ( $blog_list as $blog ) {
switch_to_blog( $blog );
// Send blog table prefix to creation function
ch8bt_create_table( $wpdb->get_blog_prefix() );
}
switch_to_blog( $start_blog );
return;
}
}
// Create table on main blog in network mode or single blog
ch8bt_create_table( $wpdb->get_blog_prefix() );
}
While this will handle creating custom tables in all the existing network sites when the plugin is activated, additional code needs to be put in place to create the additional table when new sites are created:
// Register function to be called when new blogs are added
// to a network site
add_action( 'wpmu_new_blog', 'ch8bt_new_network_site' );
function ch8bt_new_network_site( $blog_id ) {
global $wpdb;
// Check if this plugin is active when new blog is created
// Include plugin functions if it is
if ( !function_exists( 'is_plugin_active_for_network' ) ) {
require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}
// Select current blog, create new table and switch back
if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) {
$start_blog = $wpdb->blogid;
switch_to_blog( $blog_id );
// Send blog table prefix to table creation function
ch8bt_create_table( $wpdb->get_blog_prefix() );
switch_to_blog( $start_blog );
}
}
The ch8bt_create_table function itself does not require any modifications, since it was already designed to receive a table prefix from other functions and use it to build a query.