• Resolved jkhongusc

    (@jkhongusc)


    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();
     }

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    ?????? Advisor and Activist

    You can fix the code yourself. Log in with the same ID/password you used to post here, edit, done ??

    Thread Starter jkhongusc

    (@jkhongusc)

    Mika – Thanks updating the Codex was amazingly simple.

    Chris Reynolds

    (@jazzs3quence)

    restore_current_blog_id doesn’t exist (at least, it didn’t when I just tried to use it & I can’t find it in core). I’m assuming that’s just a typo & I fixed it in the codex. It should just be restore_current_blog. ??

    Thread Starter jkhongusc

    (@jkhongusc)

    Sorry, copied someone else’s code. It was a typo.

    Fixed (in case someone else comes here):

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

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Codex switch_to_blog incorrect’ is closed to new replies.