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:
|
1 2 3 4 5 6 7 8 9 10 11 |
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; } } |
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).
|
1 2 3 4 5 6 7 8 |
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; } } |