Wordpress - How to check if a user is in a specific role?
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
}
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.