Using WordPress ‘is_user_member_of_blog()’ PHP function

The is_user_member_of_blog() WordPress PHP function checks if a user is a member of a given blog.

Usage

is_user_member_of_blog($user_id, $blog_id);

Parameters

  • $user_id (int) – Optional. The unique ID of the user. Defaults to the current user.
  • $blog_id (int) – Optional. ID of the blog to check. Defaults to the current site.

More information

See WordPress Developer Resources: is_user_member_of_blog()

Examples

Check if the current user is a member of the current blog

This example checks if the current user is a member of the current blog and displays a welcome message if they are.

$user_id = get_current_user_id();

if (is_user_member_of_blog($user_id)) {
    echo "Welcome to our blog!";
}

Check if a specific user is a member of a specific blog

This example checks if a user with ID 3 is a member of the blog with ID 7.

$user_id = 3;
$blog_id = 7;

if (is_user_member_of_blog($user_id, $blog_id)) {
    echo "User 3 is a member of Blog 7.";
}

Display a list of blogs the current user is a member of

This example retrieves all blogs and displays the names of the blogs the current user is a member of.

$user_id = get_current_user_id();
$blogs = get_sites();

foreach ($blogs as $blog) {
    if (is_user_member_of_blog($user_id, $blog->blog_id)) {
        echo "You are a member of " . $blog->blogname . "<br>";
    }
}

Restrict access to a page for non-members

This example restricts access to a specific page (with ID 42) for users who are not members of the current blog.

$user_id = get_current_user_id();
$page_id = 42;

if (!is_user_member_of_blog($user_id) && is_page($page_id)) {
    wp_redirect(home_url());
    exit;
}

Display a custom message for non-member users

This example checks if the current user is not a member of the current blog and displays a custom message.

$user_id = get_current_user_id();

if (!is_user_member_of_blog($user_id)) {
    echo "Sorry, you must be a member of this blog to view its content.";
}