Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

After every instance of switch_to_blog() you should call restore_current_blog() to restore the current (actually, previous) blog.

But if you're looping through two or more blogs and calling switch_to_blog() on each, is there any reason not to use an additional switch_to_blog() at the end of the loop to switch to the original blog rather than calling restore_current_blog() at each pass.

E.g.

Why not:

 $original_blog_id = get_current_blog_id();
 foreach( $blog_ids as $blog_id ){
    switch_to_blog( $blog_id );
    //Do stuff
 }
 switch_to_blog( $original_blog_id );

instead of:

 foreach( $blog_ids as $blog_id ){
    switch_to_blog( $blog_id );
    //Do stuff
    restore_current_blog_id();
 }
share|improve this question
Now I understand this, thanks for correcting that answer of mine ;) Am revising everything. – brasofilo Mar 3 at 10:55

1 Answer

up vote 6 down vote accepted

If you want to run over multiple blogs there is no need to restore the previous blog each time. The only thing that grows is $GLOBALS['_wp_switched_stack'] – an array with blog IDs, nothing to worry about.

But keep in mind, restore_current_blog() will not work anymore after the second switch, because it uses the previous blog – which is not the first blog then. So store the first blog ID, and call switch_to_blog( $first_blog_id ); instead of restore_current_blog() when you are done.

share|improve this answer
Thought there wasn't any reason not to. Was confused why restore_current_blog() didn't just retrive the previous blog ID and call switch_to_blog() - a brief look at the code source and it seems there's a bit of code duplication... – Stephen Harris Mar 2 at 20:52
great info. Didn´t know that . Maybe restore_current_blog() should have switched the name to restore_previous_blog(). or maybe change the whole function´s own functionality to operate as a real restore_main_blog(). trac material. – krembo99 Apr 11 at 3:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.