When I call switch_to_blog()
with a blog id, I don’t know whether that blog actually exists. The function returns always true
.
Test case:
switch_to_blog(PHP_INT_MAX);
$post = get_post(1);
restore_current_blog();
This will result in database errors that are exposed to the user. How can I prevent that?
Real-world use case
I was the lead developer of MultilingualPress. When a user translates a post, she gets a screen like this:
Now the following can happen:
- She saves the post successfully and continues translating the post.
- Another user, a network admin, deletes the German blog while she is writing.
- She hits save again and gets database errors.
I want to avoid that scenario. How can I check quickly if the target blog exists? I call switch_to_blog()
very often in multiple different classes, so it has to be fast.
@G.M.’s idea to cache the check has lead me to the following helper function. I’ve put it into the global namespace to have it available everywhere.
The function doesn’t say anything about the blog status, just if it exists and is not marked as deleted. The database query is very fast (0.0001 seconds) and runs just one query per site id, no matter how often the function is called.
Usage
You could use get_site with the id of the blog to archieve this.
From the docs (https://developer.wordpress.org/reference/functions/get_site/):
returns (WP_Site|null) The site object or null if not found.
So all you have to do is something like this: