restore_current_blog() vs. multiple switch_to_blog() followed by removing $GLOBALS[‘_wp_switched_stack’]

Short answer is NO. That is an ugly hack =) More global variables are affect than the ones that you are var_dump’ing. Here are the globals that I found affected: $wpdb, $wp_roles, $wp_object_cache, $global_groups, $GLOBALS[‘_wp_switched_stack’], $GLOBALS[‘blog_id’], and $GLOBALS[‘table_prefix’]. There could be more. I found that $wpdb was another major variable that was altered by switch_to_blog(). Try var_dump’ing $wpdb in your test and you will see the effect. Any APIs relying on those globals could be affected if you do not “Always pair switch_to_blog() with restore_current_blog()”

Long answer is “depends on the situation.” I would say the statement “After every instance of switch_to_blog() you need to call restore_current_blog()” is the best practice and generally true. But there are situations where you do not need to return to the originial blog or do restore_current_blog(). For example, I created an admin plugin which altered a users role across all blogs. It iterated through all the blogs in the network using switch_to_blog, called other WP APIs (that did not rely on those globals), and ended immediately. Hence no need to restore_current_blog(). YMMV depending on where and how switch_to_blog() is used.

Leave a Comment