Tapping into switch_to_blog() Function Performance

It just happened that in my WordPress-related work I focused mostly on WordPress Multisite. I had a couple of big client projects in the past, then I developed WordPress plugins for multisite specifically, for example this one or this another one and here we go.

So I have quite a picture in my mind how the things should work the best.

In this tutorial I am about to talk about switch_to_blog() function, especially about its usage within a loop:

First of all let me show you a code snippet I am talking about.

$sites = get_sites( array( 'fields' => 'ids' ) );

foreach( $sites as $site_id ) {
	switch_to_blog( $site_id );
	$page = get_page_by_path( 'about', ARRAY_A );
	if( $page ) {
		wp_trash_post( $page->ID );
	}
	restore_current_blog();
}

In this example we’re using the following functions within the loop:

And the question is what if we move restore_current_blog() function outside the loop? So we can switch back just one time instead of a lot of times. But there is a problem – restore_current_blog() always switches to the previous site, but not to the original one, so if we move it after } we’re just going to switch to a previous site in a loop and it doesn’t help at all. But why not to use switch_to_blog() instead to switch to the first one?

$first_blog_id = get_current_blog_id();
$switched_stack = $GLOBALS[ '_wp_switched_stack' ]; // Array( 3, 4, 5, 10, etc )
$is_switched = $GLOBALS[ 'switched' ]; // false or true

foreach( $sites as $site_id ) {
	switch_to_blog( $site_id );
	$page = get_page_by_path( 'about', ARRAY_A );
	if( $page ) {
		wp_trash_post( $page->ID );
	}
}

switch_to_blog( $first_blog_id );
$GLOBALS[ '_wp_switched_stack' ] = $switched_stack;
$GLOBALS[ 'switched' ] = $is_switched;

Let me explain this code to you:

The more sites you have the more you win in performance! Thoughts?

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X