How to check if a user is in a specific role?

  • 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.

  • Rarst

    Rarst Correct answer

    10 years ago

    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 know this post is answered a long time ago but if someone happens to get here... look at the documentation once more for current_user_can() -> "Do not pass a role name to current_user_can(), as this is not guaranteed to work correctly (see #22624). Instead, you may wish to try the check user role function put together by AppThemes." (http://codex.wordpress.org/Function_Reference/current_user_can)

    ^ There is a bracket missing in the if statement

    @Aajahid edited :)

    If not using multisite, I still prefer the simplicity of `current_user_can('editor')`

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM