Home » Php » php – Get user role by ID WordPress

php – Get user role by ID WordPress

Posted by: admin April 23, 2020 Leave a comment


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.

How to&Answers:

You can’t get user role directly. First, you have to get the user_meta_data, and it will return an Object that will contain user roles.



$user_roles=$user_meta->roles; //array of roles the user is part of.


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.


// 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';


$user_meta = get_userdata($user_id);
$user_roles = $user_meta->roles;

if ( in_array( 'administrator', $user_roles, true ) ) {
    //echo User is a administrator';


hello try this optimal code

if (get_userdata($post->post_author)->roles[0] == 'your_specified_role'){
   echo 'role exist';
   echo 'role does not exist';