Check WordPress User Role By ID

While working on a membership site I wanted to retrieve a user’s role by their user id, but I couldn’t find a quick function to do this. WordPress does provide the WP_User object which gives us quick access to all user information, including user roles. To get the user role by a given ID we can do the following in php:

[php]

function get_user_roles( $id )  {
$user = new WP_User( $user_id ); // this gives us access to all the useful methods and properties for this user

if ( $user ) {
$roles = $user->roles; // returns an array of roles
return $roles;
}  else {
return false;
}

}

[/php]

It’s useful to note that it’s possible for a user to have multiple roles, even though most sites and plugins don’t utilize this possibility. What if you want to check if a user has a certain role? We can write a simple function for that as well. In my case I wanted to check if they have the custom role of teacher (a conditional function).

[php]
function user_has_role( $id, $role = ‘teacher’ ){
$roles = get_user_roles( $id ); // retrieves an array of roles
if ( $roles && in_array ( $role, $roles ) ) { // checks if specified role is listed
return true;
} else {
return false;
}
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *

Current day month ye@r *