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.
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:I was looking for a way to get a user’s role using the user’s id. Here is what I came up with:
Then, an
is_user_in_role()
function could be implemented like so:You can also just create a new user object:
Not sure what version
get_user_roles_by_user_id
was removed in, but it’s no longer an available function.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();
Here is a function that accepts a user and role for greater flexibility:
This is old post but here is one universal function what working on the all WordPress versions.
With this function you can search logged in user by role or by user ID/email. Also accept user roles array.