Skip to main content

Bulk Update WordPress Multisite Subsites

By June 30, 2018Blog, PHP, Wordpress, WP-CLI
Allure Web Solutions Code Snippet

Imagine you have a multisite with many similar client sites. Perhaps you have a plugin or custom data stored about each subsite. One day you have to update that custom data across all your subsites. Below is one method for bulk updating a wordpress multisite.

The Script

<?php
require( './wp-load.php' );

$sites = get_sites( array( 'number' => false ) );

foreach ( $sites as $site ) {
	switch_to_blog( $site->blog_id );
	if ( get_option( 'template' ) == 'template-name' ) {
		perform_actions();
	}
	restore_current_blog();
}

function perform_actions() {
    // perform actions
}

On line 8 we test for sites that we want to update. For example, all your subsites may share a theme as in the example. Or we can check if they have a certain plugin.

Inside the perform_actions function we write the code for the update. For example, if we want to update a particular ACF field on an options page, we can do something like this inside the perform_actions functions:

$field = get_field( 'field_name', 'option' );
$field['subfield'] = "updated information";
update_field('field_name', 'option');

How To Run The Script

You have two options to run the script. The first is to add it to your theme or plugin that is shared across all the WordPress subsites that you want to update.

The second option is to use WP-CLI.

Put the script into a file called update-subsites.php in your web root. Then run this WP-CLI command wp eval-file update-subsites.php

allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017