Using WordPress ‘get_blogs_of_user()’ PHP function

The get_blogs_of_user() WordPress PHP function retrieves the sites a user belongs to.

Usage

get_blogs_of_user( $user_id, $all )

Custom Example:

Input: get_blogs_of_user( 1 )

Output: Array of site objects the user with ID 1 belongs to.

Parameters

  • $user_id (int) – Required. The user ID.
  • $all (bool) – Optional. Set to true to retrieve all sites, or false to only retrieve sites that are not marked as deleted, archived, or spam. Default is false.

More information

See WordPress Developer Resources: get_blogs_of_user

Examples

Display list of sites a user belongs to

This code displays the list of sites the user with ID 1 belongs to.

$user_id = 1;
$sites = get_blogs_of_user( $user_id );

foreach ( $sites as $site ) {
    echo "Site Name: " . $site->blogname . " | Site URL: " . $site->siteurl . "<br>";
}

Get all sites, including deleted, archived, and spam

This code retrieves all sites the user with ID 1 belongs to, including deleted, archived, and spam sites.

$user_id = 1;
$all_sites = true;
$sites = get_blogs_of_user( $user_id, $all_sites );

Count the number of sites a user belongs to

This code calculates and displays the number of sites the user with ID 1 belongs to.

$user_id = 1;
$sites = get_blogs_of_user( $user_id );
$site_count = count( $sites );

echo "User belongs to " . $site_count . " sites.";

Get specific site details for a user

This code retrieves and displays the details for the first site the user with ID 1 belongs to.

$user_id = 1;
$sites = get_blogs_of_user( $user_id );
$first_site = reset( $sites );

echo "Site Name: " . $first_site->blogname . " | Site URL: " . $first_site->siteurl;

Check if user belongs to a specific site

This code checks if the user with ID 1 belongs to the site with ID 2.

$user_id = 1;
$site_id_to_check = 2;
$sites = get_blogs_of_user( $user_id );

if ( array_key_exists( $site_id_to_check, $sites ) ) {
    echo "User belongs to site with ID 2.";
} else {
    echo "User does not belong to site with ID 2.";
}