Using WordPress ‘get_id_from_blogname()’ PHP function

The get_id_from_blogname() WordPress PHP function retrieves a site’s ID given its (subdomain or directory) slug.

Usage

$slug = 'example-site';
$site_id = get_id_from_blogname($slug);

Parameters

  • $slug (string) – The site’s slug for which you want to retrieve the ID.

More information

See WordPress Developer Resources: get_id_from_blogname()

Examples

Get site ID from slug

Retrieve the site ID for a given slug and display it.

$slug = 'example-site';
$site_id = get_id_from_blogname($slug);
echo "The site ID for '$slug' is: $site_id";

Display site details based on slug

Retrieve site details using the site ID obtained from the slug.

$slug = 'example-site';
$site_id = get_id_from_blogname($slug);
$site_details = get_blog_details($site_id);
print_r($site_details);

Switch to another site using slug

Switch to another site within a multisite network using its slug.

$slug = 'another-site';
$site_id = get_id_from_blogname($slug);
switch_to_blog($site_id);
// Do great things.
restore_current_blog();

Check if a site with a specific slug exists

Determine if a site with a specific slug exists within a multisite network.

$slug = 'example-site';
$site_id = get_id_from_blogname($slug);
if ($site_id) {
    echo "The site with slug '$slug' exists!";
} else {
    echo "The site with slug '$slug' does not exist.";
}

List all posts from a site using its slug

List all posts from a site in a multisite network using the site’s slug.

$slug = 'example-site';
$site_id = get_id_from_blogname($slug);
switch_to_blog($site_id);

$args = array(
    'post_type' => 'post',
    'posts_per_page' => -1
);
$posts_query = new WP_Query($args);

if ($posts_query->have_posts()) {
    while ($posts_query->have_posts()) {
        $posts_query->the_post();
        echo '<h2>' . get_the_title() . '</h2>';
    }
    wp_reset_postdata();
} else {
    echo 'No posts found.';
}

restore_current_blog();