switch_to_blog( int $new_blog_id, bool $deprecated = null ): true

Switches the current blog.

Description

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() .

Things that aren’t switched:

  • plugins. See #14941

See also

Parameters

$new_blog_idintrequired
The ID of the blog to switch to. Default: current blog.
$deprecatedbooloptional
Not used.

Default:null

Return

true Always returns true.

Source

function switch_to_blog( $new_blog_id, $deprecated = null ) {
	global $wpdb;

	$prev_blog_id = get_current_blog_id();
	if ( empty( $new_blog_id ) ) {
		$new_blog_id = $prev_blog_id;
	}

	$GLOBALS['_wp_switched_stack'][] = $prev_blog_id;

	/*
	 * If we're switching to the same blog id that we're on,
	 * set the right vars, do the associated actions, but skip
	 * the extra unnecessary work
	 */
	if ( $new_blog_id == $prev_blog_id ) {
		/**
		 * Fires when the blog is switched.
		 *
		 * @since MU (3.0.0)
		 * @since 5.4.0 The `$context` parameter was added.
		 *
		 * @param int    $new_blog_id  New blog ID.
		 * @param int    $prev_blog_id Previous blog ID.
		 * @param string $context      Additional context. Accepts 'switch' when called from switch_to_blog()
		 *                             or 'restore' when called from restore_current_blog().
		 */
		do_action( 'switch_blog', $new_blog_id, $prev_blog_id, 'switch' );

		$GLOBALS['switched'] = true;

		return true;
	}

	$wpdb->set_blog_id( $new_blog_id );
	$GLOBALS['table_prefix']       = $wpdb->get_blog_prefix();
	$GLOBALS['blog_id']            = $new_blog_id;
	$GLOBALS['wp_template_path']   = null;
	$GLOBALS['wp_stylesheet_path'] = null;

	if ( function_exists( 'wp_cache_switch_to_blog' ) ) {
		wp_cache_switch_to_blog( $new_blog_id );
	} else {
		global $wp_object_cache;

		if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) ) {
			$global_groups = $wp_object_cache->global_groups;
		} else {
			$global_groups = false;
		}

		wp_cache_init();

		if ( function_exists( 'wp_cache_add_global_groups' ) ) {
			if ( is_array( $global_groups ) ) {
				wp_cache_add_global_groups( $global_groups );
			} else {
				wp_cache_add_global_groups(
					array(
						'blog-details',
						'blog-id-cache',
						'blog-lookup',
						'blog_meta',
						'global-posts',
						'networks',
						'network-queries',
						'sites',
						'site-details',
						'site-options',
						'site-queries',
						'site-transient',
						'rss',
						'users',
						'user-queries',
						'user_meta',
						'useremail',
						'userlogins',
						'userslugs',
					)
				);
			}

			wp_cache_add_non_persistent_groups( array( 'counts', 'plugins', 'theme_json' ) );
		}
	}

	/** This filter is documented in wp-includes/ms-blogs.php */
	do_action( 'switch_blog', $new_blog_id, $prev_blog_id, 'switch' );

	$GLOBALS['switched'] = true;

	return true;
}

Hooks

do_action( ‘switch_blog’, int $new_blog_id, int $prev_blog_id, string $context )

Fires when the blog is switched.

Changelog

VersionDescription
MU (3.0.0)Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Multiple switches

    foreach( $blog_ids as $blog_id ){
        switch_to_blog( $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() .

  2. Skip to note 8 content

    I was a little confused with the switch_to_blog() functionality when I first started using it. This function only affects the database which is being accessed on the network. I cannot access blocks of code, classes, functions, or variables that exist within a specific blog on the network. By extension, this also means that I cannot access themes or plugins that only exist on one site on the network. I was hoping for a little more power with this function before I realized that this was limited to site data being stored in the database.

    The following example does not work:

    Site 1 --> Site1_only_plugin --> Site1_only_plugin_function()

    That is, Site 1 has a unique plugin that has a bit of functionality that I want to access on Site 2 (or anywhere else on the network) without loading the full plugin to Site 2. I might be tempted to do something like this from Site 2:

    switch_to_blog( $site1 );
    
    $var = site1_only_plugin_function();
    
    restore_current_blog();

    This does not work. I can only use the switch_to_blog() functionality to access database values from other sites on the network. Here’s an example that does work:

    Site 1 --> Site1_only_plugin --> Site1_only_plugin_function()--> add_option( 'Site1_only_plugin_option', $var )

    The plugin on Site 1 has first set a value in the Site 1 database. I can then access that value in the options table from anywhere on the network as follows:

    switch_to_blog( $site1 );
    
    $var = get_option( 'Site1_only_plugin_option' );
    
    restore_current_blog();
  3. Skip to note 10 content

    Description

    Restores previous blog after a switch_to_blog call.

    Contrary to the function’s name, this does NOT restore the original blog but the previous blog. Calling `switch_to_blog() ` twice in a row and then calling this function will result in being on the blog set by the first `switch_to_blog() ` call.

  4. Skip to note 11 content

    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'
    	)
    );
    ?>

You must log in before being able to contribute a note or feedback.