How to check if a user is in a specific role?
-
16-10-2019 - |
Question
I have a pretty specific requirement to show different text in a field label on the user profile page based on the current user's role. I can't seem to figure out how to check whether the current use is an "author".
I am looking for a function like:
is_user_in_role($user, "author");
I imagine this is pretty simple, but I have searched for too long without an answer so I thought I would post it here.
Solution
If you only need this for current user current_user_can()
accepts both roles and capabilities.
UPDATE: Passing a role name to current_user_can()
is no longer guaranteed to work correctly (see #22624). Instead, you may wish to check user role:
$user = wp_get_current_user();
if ( in_array( 'author', (array) $user->roles ) ) {
//The user has the "author" role
}
OTHER TIPS
I was looking for a way to get a user's role using the user's id. Here is what I came up with:
function get_user_roles_by_user_id( $user_id ) {
$user = get_userdata( $user_id );
return empty( $user ) ? array() : $user->roles;
}
Then, an is_user_in_role()
function could be implemented like so:
function is_user_in_role( $user_id, $role ) {
return in_array( $role, get_user_roles_by_user_id( $user_id ) );
}
You can also just create a new user object:
$user = new WP_User( $user_id );
if ( ! empty( $user->roles ) && is_array( $user->roles ) && in_array( 'Some_role', $user->roles ) ) {
return true;
}
Not sure what version get_user_roles_by_user_id
was removed in, but it's no longer an available function.
Here is a function that accepts a user and role for greater flexibility:
function my_has_role($user, $role) { $roles = $user->roles; return in_array($role, (array) $user->roles); } if(my_has_role($user, 'some_role')) { //do stuff }
Calling roles on User Object $user->roles
do not return all the roles. The correct way to find if the user has a role or capability is following. (This works in wp version 2.0.0 and greater.) The following function works with user id you can get the current user id by $current_user_id = get_current_user_id();
/**
* Returns true if a user_id has a given role or capability
*
* @param int $user_id
* @param string $role_or_cap Role or Capability
*
* @return boolean
*/
function my_has_role($user_id, $role_or_cap) {
$u = new \WP_User( $user_id );
//$u->roles Wrong way to do it as in the accepted answer.
$roles_and_caps = $u->get_role_caps(); //Correct way to do it as wp do multiple checks to fetch all roles
if( isset ( $roles_and_caps[$role_or_cap] ) and $roles_and_caps[$role_or_cap] === true )
{
return true;
}
}