@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." );