WordPress MU plugin activation for each blog

<?php
 
register_activation_hook( __FILE__, 'pluginname_register_activation_hook' );
register_deactivation_hook( __FILE__, 'pluginname_register_deactivation_hook' );
 
function pluginname_create_database_table() {
    $table_name = 'plugin_table_name';
 
    if( ! pluginname_database_table_exists( $table_name ) ) {
        $sql = "CREATE TABLE " . $table_name . " (
				id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
				name VARCHAR(250) NOT NULL DEFAULT '',
				date_created DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00'
				) CHARACTER SET utf8 COLLATE utf8_unicode_ci;";
 
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
}
 
function pluginname_database_table_exists( $table_name ) {
    global $wpdb;
    return strtolower( $wpdb->get_var("SHOW TABLES LIKE '$table_name'") ) == strtolower( $table_name );
}
 
function pluginname_register_activation_hook() {
    if( function_exists('is_multisite') && is_multisite() ) {
        if( isset($_GET['networkwide']) && ( $_GET['networkwide'] == 1 ) ) {
            pluginname_call_function_for_each_site( 'pluginname_activate' );
            return;
        }
    }
 
    pluginname_activate(); // otherwise do it for a single blog/site
}
 
function pluginname_activate() {
    pluginname_create_database_table();
    update_option( PLUGINNAME_VERSION_KEY, PLUGINNAME_VERSION_NUM );
}
 
function pluginname_register_deactivation_hook() {
    if( function_exists( 'is_multisite' ) && is_multisite() ) {
        if( isset( $_GET['networkwide'] ) && ( $_GET['networkwide'] == 1 ) ) {
            pluginname_call_function_for_each_site( 'pluginname_deactivate' );
            return;
        }
    }
 
    pluginname_deactivate(); // otherwise do it for a single blog/site
}
 
function pluginname_deactivate() {
    delete_option( PLUGINNAME_VERSION_KEY );
}
 
 
function pluginname_call_function_for_each_site( $function ) {
    global $wpdb;
 
    // Hold this so we can switch back to it
    $root_blog = $wpdb->blogid;
 
    // Get all the blogs/sites in the network and invoke the function for each one
    $blog_ids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs"));
    foreach ($blog_ids as $blog_id) {
        switch_to_blog($blog_id);
        call_user_func($function);
    }
 
    // Now switch back to the root blog
    switch_to_blog($root_blog);
}
 
?>

Leave a Reply

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