restore_current_blog() vs switch_to_blog()

After every instance of switch_to_blog() you need to call restore_current_blog() otherwise WP will think it is in a “switched” mode and can potentially return incorrect data.

If you view the source code for both functions you will see those functions push/pop data into a global called $GLOBALS['_wp_switched_stack']. If you do not call restore_current_blog() after every switch_to_blog(), $GLOBALS['_wp_switched_stack'] will be non-empty. If $GLOBALS['_wp_switched_stack'] is non-empty WP thinks it is in a switched mode, even if you switched back to the original blog using switch_to_blog(). The switched mode function is ms_is_switched() and it affects wp_upload_dir(). If wp_upload_dir() thinks it is in a switched mode, it can return data that is incorrect. wp_upload_dir() builds URLs for the site, so it is a very critical function.

This is the correct use:

 foreach( $blog_ids as $blog_id ){
    switch_to_blog( $blog_id );
    //Do stuff
    restore_current_blog();
 }

Leave a Comment