switch_to_blog()
Switch the current blog.
This function is useful if you need to pull posts, or other information, from other blogs. You can switch back afterwards using restore_current_blog().
PHP code loaded with the originally requested site, such as code from a plugin or theme, does not switch. See #14941.
Hooks from the function
Return
true
. Always returns true.
Usage
switch_to_blog( $new_blog_id, $deprecated );
- $new_blog_id(int) (required)
- The ID of the blog to switch to.
Default: current blog - $deprecated(true|false)
- Not used.
Default: null
Examples
#1 Single Switching
Let's switch to blog 5 to display its posts and go back to the current blog.
// switch to blog 5 switch_to_blog( 5 ); // Output the data of the blog we switched to // Getting posts from blog 5 $myposts = get_posts(); foreach( $myposts as $post ){ echo esc_html( $post->post_title ) .'<br>'; } wp_reset_postdata(); // back to the current blog restore_current_blog();
#2 Multiple Switching
Before you can switch to another blog, you must first go back to the current blog...
foreach( $blog_ids as $blog_id ){ switch_to_blog( $blog_id ); // process the data of the blog to which we have switched. restore_current_blog(); }
Note: 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.
#3 global $switched note
When using switch_to_blog() outside of WordPress, you need to have the global $switched
defined. The variable for defining which blog ID to target, may also not be $blog_id, because it is used by WP Core.
The below example will NOT create a post within the correct blog_id, unless $switched
is defined.
<?php require_once '../wp-load.php'; global $switched; $blog_id_target = 2; switch_to_blog( $blog_id_target ); // Create a post programmatically, for blog 2. $id = wp_insert_post( array( 'post_author' => 1, 'post_status' => 'publish', 'post_type' => 'custom_post_type', 'post_content' => 'Post body here', 'post_title' => 'Post title here' ) ); ?>
Notes
- See: restore_current_blog()
- Global. wpdb. $wpdb WordPress database abstraction object.
- Global. Int. $blog_id
- Global. Array. $_wp_switched_stack
- Global. true|false. $switched
- Global. String. $table_prefix The database table prefix.
- Global. WP_Object_Cache. $wp_object_cache
Changelog
Since 3.0.0 | Introduced. |