19

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:

enter image description here

Now the following can happen:

  1. She saves the post successfully and continues translating the post.
  2. Another user, a network admin, deletes the German blog while she is writing.
  3. 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.

8
  • How about $wpdb->blogid; and the hook wp_insert_post_data ?
    – JMau
    Commented Mar 18, 2014 at 0:49
  • @JMau get_post() is just a read. There can be a long pause between the last save and the next edit screen reload.
    – fuxia
    Commented Mar 18, 2014 at 0:54
  • 5
    A per-request cached SQL query for blog_id in wp_blogs table (where deleted = 0)?
    – gmazzap
    Commented Mar 18, 2014 at 1:32
  • 1
    @G.M. SELECT blog_id FROM {$wpdb->blogs} WHERE site_id = %d AND public = '1' AND archived = '0' AND spam = '0' AND deleted = '0'
    – kaiser
    Commented Mar 18, 2014 at 2:58
  • @toscho Thinking out loud... There's 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)?
    – kaiser
    Commented Mar 18, 2014 at 3:02

3 Answers 3

11

@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.

if ( ! function_exists( 'blog_exists' ) ) {

    /**
     * Checks if a blog exists and is not marked as deleted.
     *
     * @link   http://wordpress.stackexchange.com/q/138300/73
     * @param  int $blog_id
     * @param  int $site_id
     * @return bool
     */
    function blog_exists( $blog_id, $site_id = 0 ) {

        global $wpdb;
        static $cache = array ();

        $site_id = (int) $site_id;

        if ( 0 === $site_id )
            $site_id = get_current_site()->id;

        if ( empty ( $cache ) or empty ( $cache[ $site_id ] ) ) {

            if ( wp_is_large_network() ) // we do not test large sites.
                return TRUE;

            $query = "SELECT `blog_id` FROM $wpdb->blogs
                    WHERE site_id = $site_id AND deleted = 0";

            $result = $wpdb->get_col( $query );

            // Make sure the array is always filled with something.
            if ( empty ( $result ) )
                $cache[ $site_id ] = array ( 'do not check again' );
            else
                $cache[ $site_id ] = $result;
        }

        return in_array( $blog_id, $cache[ $site_id ] );
    }
}

Usage

if ( ! blog_exists( $blog_id ) )
    return new WP_Error( '410', "The blog with the id $blog_id has vanished." );
3
  • why $wpdb->get_results + wp_list_pluck instead of only (int) $wpdb->get_var? however +1, and I think that something similar should be in core switch_to_blog...
    – gmazzap
    Commented Mar 18, 2014 at 14:07
  • @G.M. get_var() returns just one result. I have used get_col() now, and I made sure an empty result is not fetched again.
    – fuxia
    Commented Mar 18, 2014 at 20:21
  • Ah ok... I better read the query now, you get all the blog ids for a specific site id, at first read I thougt you get only one blog id at time (the one passed to function)... sure the array way is better. I'm sorry isn't possible +1 again :)
    – gmazzap
    Commented Mar 18, 2014 at 20:37
2
if( get_blog_details( [ 'blog_id' => $blogIdToTest ] ) ) {
 // Exists
} else {
 // Dont exists
}
0

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:

// Replace PHP_INT_MAX with the var which holds the site id you want to check against
if(!is_null(get_site(PHP_INT_MAX)){
//do stuff if site exists
}
else{
// do stuff if the site doesn't exists (anymore)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.