diff --git a/src/Site.php b/src/Site.php index 6ae2fe561..0061a27d8 100644 --- a/src/Site.php +++ b/src/Site.php @@ -217,17 +217,30 @@ public function wp_object(): ?WP_Site /** * Switches to the blog requested in the request * - * @param string|integer|null $site_name_or_id + * @param string|integer|null $blog_identifier The name or ID of the blog to switch to. If `null`, the current blog. * @return integer with the ID of the new blog */ - protected static function switch_to_blog($site_name_or_id) + protected static function switch_to_blog($blog_identifier = null): int { - if ($site_name_or_id === null) { - $site_name_or_id = \get_current_blog_id(); + $current_id = \get_current_blog_id(); + + if ($blog_identifier === null) { + $blog_identifier = $current_id; + } + + $info = \get_blog_details($blog_identifier, false); + + if (false === $info) { + return $current_id; } - $info = \get_blog_details($site_name_or_id); - \switch_to_blog($info->blog_id); - return $info->blog_id; + + $blog_identifier = $info->blog_id; + + if ((int) $current_id !== (int) $blog_identifier) { + \switch_to_blog($blog_identifier); + } + + return (int) $blog_identifier; } /** diff --git a/tests/test-timber-multisite.php b/tests/test-timber-multisite.php index 059646231..bb637681a 100644 --- a/tests/test-timber-multisite.php +++ b/tests/test-timber-multisite.php @@ -53,6 +53,7 @@ public function testPostGettingAcrossSites() $this->factory->post->create([ 'post_title' => array_pop($post_titles), ]); + restore_current_blog(); } $timber_posts = []; @@ -108,6 +109,7 @@ public function testPostGettingAcrossSitesNoArgs() $this->factory->post->create([ 'post_title' => 'Zebras are good on site ID = ' . $site_id, ]); + restore_current_blog(); } $this->go_to('/'); $timber_posts = []; @@ -144,8 +146,11 @@ public function testPostSearchAcrossSites() return; } $site_ids[] = self::createSubDomainSite('foo.example.org', 'My Foo'); + restore_current_blog(); $site_ids[] = self::createSubDomainSite('quack.example.org', "Ducks R Us"); + restore_current_blog(); $site_ids[] = self::createSubDomainSite('duck.example.org', "More Ducks R Us"); + restore_current_blog(); $post_titles = ["I don't like zebras", "Zebra and a half", "Have a zebra of a time"]; $others = $this->factory->post->create_many(8); @@ -154,6 +159,7 @@ public function testPostSearchAcrossSites() $this->factory->post->create([ 'post_title' => array_pop($post_titles), ]); + restore_current_blog(); } $timber_posts = [];