Home News Write a Plugin for WordPress Multi-Site

Write a Plugin for WordPress Multi-Site

by Phill

Presently, we have to undergo a non-trivial procedure to turn on multisite capability. But, there are already plugins that attempt to automate this procedure in simple. While this procedure gets simpler and more compact, the multisite capacity will probably see broader adoption.

As its name implies, WordPress multisite lets us control several sites from one WordPress dashboard. WordPress.com for instance, utilizes this multisite capability, therefore it’s a wonderful spot to visit if you would like to quickly try out the multisite port and works.

From one WordPress setup, we have an whole database along with an total WordPress installation area specializing in one site. Plugins can be ensured that there’s just one articles table (wp_posts), one remarks desk (wp_comments), 1 links table (wp_links) etc.)

Likewise, each plugin has their own file area that need just be committed to one blog. Some plugins can cache documents in this space.

At a multisite WordPress setup, our database may include tables for every one our sites. Thus, we might have several articles tables (wp_posts, wp2_posts, wp3_posts) multiple opinions tables, multiple hyperlinks , etc..

Additional each site no longer has its own setup file area. Rather, all sites share a frequent plugin file-space.

Some plugins might have to produce local pages/files that are particular to a site (e.g., a caching plugin). At a multisite setup, it’s essential for all these plugins to make different file areas for every site and keep tabs on every one of these regions.

When composing a WordPress multisite plugin, it’s absolutely imperative that you don’t make any database calls for hard-coded dining table titles. Rather, constantly extract the titles from the wpdb worldwide thing.

For Instance, If you Want to implement an SQL command on the articles table, then DO NOT use wp_posts since the table title —

1
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM wp_posts");

Rather, use the articles table name included within the wpdb Worldwide item —

1
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts");

By linking our plugin into the $wpdb objectwe could rest assured that our plugin is getting the proper tables for the current site.

The listing of tables pointed out by the wpdb Worldwide object comprise —

Remarks
commentmeta
Connections
Choices
postmeta
Articles
terms
term_relationships
term_taxonomy
Global multisite tables comprise —

usermeta
users
Sites
blog_versions
registration_log
signups
Website
sitecategories

WordPress Multisite Plugin — Establishing a Table

On occasion, it’s crucial to make our tables. From the example belowwe produce a word metadata table to get our plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Create a term metadata table where $type = metadata type
global $wpdb;
$table_name = $wpdb->prefix . $type . 'meta';
if ($wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'") != $table_name) {
          
    shiba_create_metadata_table($table_name, $type);
}
function shiba_create_metadata_table($table_name, $type) {
    global $wpdb;
    if (!empty ($wpdb->charset))
        $charset_collate = "DEFAULT CHARACTER SET {$wpdb->charset}";
    if (!empty ($wpdb->collate))
        $charset_collate .= " COLLATE {$wpdb->collate}";
            
        $sql = "CREATE TABLE IF NOT EXISTS {$table_name} (
            meta_id bigint(20) NOT NULL AUTO_INCREMENT,
            {$type}_id bigint(20) NOT NULL default 0,
    
            meta_key varchar(255) DEFAULT NULL,
            meta_value longtext DEFAULT NULL,
                
            UNIQUE KEY meta_id (meta_id)
        ) {$charset_collate};";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

Line 2 — Place our database name by pre-pending it using the ideal table prefix.
Line 3 — Check to determine if table exists. Only make a new table in case one doesn’t already exists.

When a plugin becomes triggered, we might run particular initialization works by linking them into the register_activation_hook function. By way of instance, we might create our plugin during the activation procedure.

In one site configuration, we conduct our activation feature, create one table, and we’re done. Nonetheless, in a multisite setup, we’ll have to make tables for every website inside our community. Thus, we must iterate over every site and operate our plugin activation work for each and each of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
register_activation_hook( __FILE__, 'shiba_activate' );
function shiba_activate($networkwide) {
    global $wpdb;
                
    if (function_exists('is_multisite') && is_multisite()) {
        // check if it is a network activation - if so, run the activation function for each blog id
        if ($networkwide) {
                    $old_blog = $wpdb->blogid;
            // Get all blog ids
            $blogids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs");
            foreach ($blogids as $blog_id) {
                switch_to_blog($blog_id);
                _shiba_activate();
            }
            switch_to_blog($old_blog);
            return;
        }  
    }
    _shiba_activate();     
}
function _shiba_activate() {
        // Add initial plugin options here
    $current_theme = get_current_theme();
    add_option('shiba_bg_theme', $current_theme);
    // Create term metadata table if necessary
    global $wpdb;
        $type = 'shiba_term';
        $table_name = $wpdb->prefix . $type . 'meta';
    if ($wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'") != $table_name) {
        shiba_create_metadata_table($table_name, $type);
        }
}

Line 7 — Check if plugin was triggered for the whole blog network.
Lines 9-13 — Iterate over every site inside our community, and operate our activation role for every site.
Line 17 — When multisite capacity isn’t on, or when plug is only activated for one site, then simply run our activation purpose after.

We might also wish to run our plug in activation function if a new site is created.

1
2
3
4
5
6
7
8
9
10
11
12
add_action( 'wpmu_new_blog', 'new_blog', 10, 6);       
function new_blog($blog_id, $user_id, $domain, $path, $site_id, $meta ) {
    global $wpdb;
    if (is_plugin_active_for_network('shiba-custom-background/shiba-custom-background.php')) {
        $old_blog = $wpdb->blogid;
        switch_to_blog($blog_id);
        _shiba_activate();
        switch_to_blog($old_blog);
    }
}

 

WordPress Multisite Plugin – Deactivation, and Uninstall

In exactly the exact same manner that we would like to initialize each site if our plugin is community triggered, we’ll also wish to wash up every website if our plugin is community deactivated. We can unite both activate and deactivate acts as follows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
register_activation_hook( __FILE__, 'shiba_activate' );
register_deactivation_hook( __FILE__, 'shiba_deactivate' );
    
function my_network_propagate($pfunction, $networkwide) {
    global $wpdb;
    if (function_exists('is_multisite') && is_multisite()) {
        // check if it is a network activation - if so, run the activation function
        // for each blog id
        if ($networkwide) {
            $old_blog = $wpdb->blogid;
            // Get all blog ids
            $blogids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->blogs}");
            foreach ($blogids as $blog_id) {
                switch_to_blog($blog_id);
                call_user_func($pfunction, $networkwide);
            }
            switch_to_blog($old_blog);
            return;
        }  
    }
    call_user_func($pfunction, $networkwide);
}
function shiba_activate($networkwide) {
    my_network_propagate('_my_activate', $networkwide);
}
function shiba_deactivate($networkwide) {
    my_network_propagate('_my_deactivate', $networkwide);
}

Ultimately, we simply have to replicate our deactivation purpose when a site is deleted, and be certain our uninstall.php file implements cleanup operations for all of the sites within our WordPress multisite network. This practice is quite like that which we’ve done previously so we are not going to repeat it here.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More