When you're developing a new plugin you may need to run some code on the activation of the plugin. For example if your plugin requires a database table to be installed on the site then you need to make sure that this database table is created on plugin activation. To activate a hook to run when the plugin is activated you can use a WordPress function called register_activation_hook.
register_activation_hook( __FILE__, 'plugin_activated' );
function plugin_activated()
{
// run code on plugin activated
}
The problem with this is that if you're running a multisite WordPress install you might need the code to run on each of your multisites. To be able to run some code on the activation of the plugin on each site you need check that multisite is installed, loop through all the blogs and run the code on each site using the blog ID to create the new tables.
function plugin_activated()
{
if ( is_multisite() )
{
global $wpdb;
foreach ($wpdb->get_col("SELECT blog_id FROM $wpdb->blogs") as $blogId) {
switch_to_blog($blogId);
register_new_db_table( $blogId );
restore_current_blog();
}
} else {
register_new_db_table( get_current_blog_id() );
}
}
function register_new_db_table( $blogId )
{
// register new db table
}
register_activation_hook( __FILE__, 'plugin_activated' );
This code will use the function is_multisite() to check is multisite is installed and running. If it is then we search for all sites installed and run the same code to register the new table for that single site. Learn how to create a custom WordPress tables on plugin activation.