switch_to_blog

Advertisement

Summery Summery

Switch the current blog.

Syntax Syntax

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

Description 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

Parameters Parameters

$new_blog_id

(Required) The ID of the blog to switch to. Default: current blog.

$deprecated

(Optional) Not used.

Default value: null

Return Return

(true) Always returns true.

Source Source

File: wp-includes/ms-blogs.php

 * @global array           $_wp_switched_stack
 * @global bool            $switched
 * @global string          $table_prefix
 * @global WP_Object_Cache $wp_object_cache
 *
 * @param int  $new_blog_id The ID of the blog to switch to. Default: current blog.
 * @param bool $deprecated  Not used.
 * @return true Always returns true.
 */
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;

	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 {

Advertisement

Changelog Changelog

Changelog
Version Description
MU (3.0.0) Introduced.

See also See also

Advertisement

Leave a Reply