Skip to content

Commit

Permalink
fix: Prevent unneeded blog switching in multisite env. (#2781)
Browse files Browse the repository at this point in the history
* rework switch_to_blog method
* remove dump paste
* remove error log, see #2210
* Make suggested typecast changes by @gchtr
* Get short version of get_blog_details()
* remove extra int cast
* proposed fixes for multisite tests
  • Loading branch information
Levdbas committed Feb 27, 2024
1 parent b048da8 commit d81f995
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 7 deletions.
27 changes: 20 additions & 7 deletions src/Site.php
Expand Up @@ -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;
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/test-timber-multisite.php
Expand Up @@ -53,6 +53,7 @@ public function testPostGettingAcrossSites()
$this->factory->post->create([
'post_title' => array_pop($post_titles),
]);
restore_current_blog();
}

$timber_posts = [];
Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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);
Expand All @@ -154,6 +159,7 @@ public function testPostSearchAcrossSites()
$this->factory->post->create([
'post_title' => array_pop($post_titles),
]);
restore_current_blog();
}

$timber_posts = [];
Expand Down

0 comments on commit d81f995

Please sign in to comment.