Skip to content
Advertisement

Get user role by ID WordPress

I need to somehow check someone’s role with only their id. I have found the current_user_can() check. But this only works for people that are logged in. How would I check for this if that user isn’t the current user? I am using a phone order system but that uses the admin/specific account to order for other people.

Advertisement

Answer

To check if a user has a specific role, you have to get a list of their roles and see if the role is listed there.

Example function:

function user_has_role($user_id, $role_name)
{
    $user_meta = get_userdata($user_id);
    $user_roles = $user_meta->roles;
    return in_array($role_name, $user_roles);
}

Example usage:

$user_is_subscriber = user_has_role(get_current_user_id(), 'subscriber');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement