get_id_from_blogname()WP 3.0.0

Retrieves a sites ID given its (subdomain or directory) slug.

No Hooks.

Return

Int|null. The site ID, or null if no site is found for the given slug.

Usage

get_id_from_blogname( $slug );
$slug(string) (required)
A site's slug.

Examples

0

#1 Get the network site ID from the name (slug) of the site

Suppose the ID of the desired site is 2, then:

// the site can have the following domain or path, depends on the multisite settings:
// blog.site.com
// site.com/blog
get_id_from_blogname( 'blog' ); //> 2
0

#2 Switching blogs based on the blogs name ($slug)

$slug = 'another-site';
$id = get_id_from_blogname( $slug );

switch_to_blog( $id );

// Do your staff

restore_current_blog();

Changelog

Since 3.0.0 Introduced.
Since 4.7.0 Converted to use get_sites().

get_id_from_blogname() code WP 6.5.3

function get_id_from_blogname( $slug ) {
	$current_network = get_network();
	$slug            = trim( $slug, '/' );

	if ( is_subdomain_install() ) {
		$domain = $slug . '.' . preg_replace( '|^www\.|', '', $current_network->domain );
		$path   = $current_network->path;
	} else {
		$domain = $current_network->domain;
		$path   = $current_network->path . $slug . '/';
	}

	$site_ids = get_sites(
		array(
			'number'                 => 1,
			'fields'                 => 'ids',
			'domain'                 => $domain,
			'path'                   => $path,
			'update_site_meta_cache' => false,
		)
	);

	if ( empty( $site_ids ) ) {
		return null;
	}

	return array_shift( $site_ids );
}