WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/switch to blog

Description

Switch the current blog to a different blog. switch_to_blog() is useful if you need to pull posts or other information from other blogs.

You can switch back afterwards using restore_current_blog(). Note that this function reverses only the last blog switching action, typically the most recent call to switch_to_blog(). See the example below on how to proceed when multiple switch_to_blog()s are used.

Things that aren't switched:

Parameters

$new_blog
(integer) (required) The id of the blog you want to switch to.
Default: current blog
$deprecated
(boolean) (optional) Deprecated argument
Default: null

Return Values

(bool) 
true is returned even when no blog exists with a Blog ID of $new_blog, or when "switching" to the current blog.

Examples

One switch

switch_to_blog( $blog_id );
// Do something
restore_current_blog();

Multiple switches

$blog_ids=get_sites();
foreach( $blog_ids as $b ){
    switch_to_blog( $b->blog_id );
    //Do stuff
    restore_current_blog();
}

If you do not call restore_current_blog() after every switch_to_blog(), WordPress can get into a state that can potentially build the wrong urls for the site. See restore_current_blog() vs switch_to_blog()

Change Log

Source File

switch_to_blog() is located in wp-includes/ms-blogs.php

Related

switch_to_blog(), ms_is_switched(), restore_current_blog(), get_current_blog_id(), wp_get_sites(), get_blog_details()