WordPress

Run Code For Multisite On Plugin Activation

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.

Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days

Comments

  1. Would the code run for every blog even if only activated on one?

    1. Paul says:

      Hi, yes it will that's what the foreach loop will handle. It will loop through all the blog IDs that you have and run the code on each blog.

Leave a Reply

Your email address will not be published. Required fields are marked *