Codex switch_to_blog incorrect
-
There are errors in the Codex for switch_to_blogs(), specifically the section on ‘Multiple switches’. Codex page I am referring to – https://codex.www.ads-software.com/Function_Reference/switch_to_blog
Story: We started using a plugin called User Role Editor and noticed immediately that urls for media were changed. We disabled the plugin and the urls were corrected. I posted all the details in the plugin forum here – https://www.ads-software.com/support/topic/improper-usage-of-switch_to_blog
In short the plugin author was following the advice in the codex for multiple switches. IMO, that advice is wrong. The codex samples says to do it this way:
$original_blog_id = get_current_blog_id(); foreach( $blog_ids as $blog_id ){ switch_to_blog( $blog_id ); //Do something } switch_to_blog( $original_blog_id );
This is wrong because restore_current_blog() needs to be called for every switch_to_blog()! This is why, each switch_to_blog() call pushes data into a global called $GLOBALS[‘_wp_switched_stack’]. restore_current_blog() is required to pop off that data. If you do not clear out $GLOBALS[‘_wp_switched_stack’], then WP thinks it is in a “switched” mode. The function is ms_is_switched() and returns true when $GLOBALS[‘_wp_switched_stack’] is not empty. That affects wp_upload_dir() which uses ms_is_switched(). wp_upload_dir() builds the urls for the site and can potentially return wrong site info when it thinks it is in a “switched” mode even when it is not.
Not sure if people agree with my assessment. And if they do, how to fix it in the Codex.
FYI the correct solution to do multiple switches:
foreach( $blog_ids as $blog_id ){ switch_to_blog( $blog_id ); //Do stuff restore_current_blog_id(); }
- The topic ‘Codex switch_to_blog incorrect’ is closed to new replies.