Get user role by WordPress ID

I need to somehow check the role of someone only with their identifier. I found a check for current_user_can() . But this only works for people who are logged in. How can I check this if this user is not the current user? I use the telephone ordering system, but I use an administrator / specific user account to order other people.

+27
php wordpress user-roles
source share
4 answers

You cannot get the user role directly. First, you should get user_meta_data, and it will return an object that will contain user roles.

The code:

 $user_meta=get_userdata($user_id); $user_roles=$user_meta->roles; //array of roles the user is part of. 
+49
source share

Information you must know before proceeding:

  • You cannot get the user role by ID directly.
  • You can get all the roles that are assigned to the user.

Let me get all the roles and check if there is a role that interests you 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'; } 
+9
source share
 $user_meta = get_userdata($user_id); $user_roles = $user_meta->roles; if ( in_array( 'administrator', $user_roles, true ) ) { //echo User is a administrator'; } 
+1
source share

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'; } 
0
source share

All Articles