57

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.

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Tristan .L
  • 829
  • 3
  • 9
  • 20
  • Like described, I use a special phone order system. Orders are sometimes placed for a specific user by (for example) admin. And when this happens I need to check the role of that original user – Tristan .L Apr 19 '16 at 14:33

4 Answers4

99

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');
Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Meathanjay
  • 2,023
  • 1
  • 18
  • 24
  • 42
    `$user_meta=get_userdata($user_id); $user_roles=$user_meta->roles; if (in_array("subscriber", $user_roles)){}` Results in a role check for subscriber. – Tristan .L Apr 19 '16 at 15:18
29

The info you need to know before you proceed:

  • You can't get user role by ID directly.
  • You can get all the roles a user is assigned to.

Let's get all the roles and check if the role you're interested in is there or now.

<?php

// Get the user object.
$user = get_userdata( $user_id );

// Get all the user roles as an array.
$user_roles = $user->roles;

// Check if the role you're interested in, is present in the array.
if ( in_array( 'subscriber', $user_roles, true ) ) {
    // Do something.
    echo 'YES, User is a subscriber';
}
Ahmad Awais
  • 33,440
  • 5
  • 74
  • 56
3

hello try this optimal code

if (get_userdata($post->post_author)->roles[0] == 'your_specified_role'){
   echo 'role exist';
}else{
   echo 'role does not exist';
}
phpier
  • 55
  • 4
-3
$user_meta = get_userdata($user_id);
$user_roles = $user_meta->roles;

if ( in_array( 'administrator', $user_roles, true ) ) {
    //echo User is a administrator';
}
  • 11
    Your answer looks an awful lot like [Ahmad's answer](https://stackoverflow.com/a/51719421/479156) of 3 months ago. Does this add anything new? – Ivar Nov 18 '18 at 16:20