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.
$wpdb->blogid;
and the hookwp_insert_post_data
?get_post()
is just a read. There can be a long pause between the last save and the next edit screen reload.SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = %d AND public = '1' AND archived = '0' AND spam = '0' AND deleted = '0'
wp_cache_switch_to_blog()
, but it only helps with persistant cache, not the default on page WP thing. Anyway, to me it's not really clear where you want to check the blog existence: When someone deletes a blog or when someone tries to write the translated post that points to a different blog (powering the same content in another language)?