WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Get a user’s role by user ID

[Resolved] Get a user’s role by user ID

  • Justin Tadlock

    @greenshady

    WordPress God

    I’ve searched high and low for some sort of function to grab a user’s role, but have yet to find a solution. I can check in the wp_capabilities table to see if a user has a particular role, but this won’t work in this particular situation.

    The problem:

    I need to grab a user’s role to use in other functions. The project I’m working on will have roles that might change, so there’s no definite set of roles (i.e., administrator, editor, etc.) like with a standard WP setup. For example, a particular role might be super_geek or uber_geek. There’s just no way for me to know what the roles will be beforehand.

    Just to clarify: I don’t need the user’s capabilities because capabilities will cross over between roles.

    Does anyone know a way of grabbing a user’s role from the database based on the user’s ID?

Viewing 15 replies - 1 through 15 (of 19 total)
  • From my notes, not exactly what you want but should get you there…

    <?php
    //list each role and each user with that role (works if logged in)
    //see http://wordpress.org/support/topic/256436 if not logged in:
    global $wp_roles;
    foreach( $wp_roles->role_names as $role => $name ) {
      $name = translate_with_context($name);
      echo '<p>List of users in the role '.$role .' ('. $name . '):</p>';
      $this_role = "'[[:<:]]".$role."[[:>:]]'";
      $query = "SELECT * FROM $wpdb->users WHERE ID = ANY (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'wp_capabilities' AND meta_value RLIKE $this_role) ORDER BY user_nicename ASC LIMIT 10000";
      $users_of_this_role = $wpdb->get_results($query);
      if ($users_of_this_role) {
        foreach($users_of_this_role as $user) {
          $curuser = get_userdata($user->ID);
          $author_post_url=get_author_posts_url($curuser->ID, $curuser->nicename);
          echo '<p>--User nicename: '.$curuser->user_nicename .', display Name: '. $curuser->display_name . ', link to author posts <a href="' . $author_post_url . '" title="' . sprintf( __( "Posts by %s" ), $curuser->user_nicename ) . '" ' . '>' . $curuser->user_nicename .'</a></p>';
        }
      }
    }
    ?>
    Justin Tadlock

    @greenshady

    WordPress God

    Yeah, that runs us into the issue of $wp_roles being empty when not logged in, which forces us to have a predefined array of roles as mentioned in the other thread.

    Just a simple example for testing, which works when logged in:

    <?php
    	global $wp_roles;
    
    	foreach ( $wp_roles->role_names as $role => $name ) :
    
    		if ( current_user_can( $role ) )
    			echo 'This user has a role of ' . $role;
    
    	endforeach;
    ?>

    So, I’m guessing the real question is how to get an array of all the user roles when not logged in.

    Justin Tadlock

    @greenshady

    WordPress God

    Thanks for pointing me in the right direction. I found my answer:
    http://core.trac.wordpress.org/attachment/ticket/5290/author-template-the_author_role.diff

    Here’s the solution (assuming you have the user ID: $user_id):

    <?php
    	$user = get_userdata( $user_id );
    
    	$capabilities = $user->{$wpdb->prefix . 'capabilities'};
    
    	if ( !isset( $wp_roles ) )
    		$wp_roles = new WP_Roles();
    
    	foreach ( $wp_roles->role_names as $role => $name ) :
    
    		if ( array_key_exists( $role, $capabilities ) )
    			echo $role;
    
    	endforeach;
    ?>

    Thanks for this…

    Now, I have another problem… I would like to display the author role on comments (like on this wordpress support site); when using this function, it show the same role for all comments ( because it’s in reality the role of the author of the commented post).
    What can I do?

    @greenshady: Thanks for your solution but it show me this warning everytime:
    Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in E:\wamp\www\s\wp-content\themes\TBlackV2\functions.php on line 225

    What’s the solution??

    Justin Tadlock

    @greenshady

    WordPress God

    An even easier way to get a user’s role:

    $user = new WP_User( $user_id );
    
    if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    	foreach ( $user->roles as $role )
    		echo $role;
    }

    Just change $user_id to a specific ID.

    kunaimedia

    @kunaimedia

    Why are you looping through $users? Can WP_User() have multiple id’s passed at once? This works just fine for one user id:

    $user = new WP_User( $user_id );
    echo $user->roles[0];

    Are there any problems with this?

    Justin Tadlock

    @greenshady

    WordPress God

    I’m not looping through $users; I’m looping through $user->roles.

    Your code will work fine assuming all your users only have a single role, which will eventually be a standard in WordPress, or if you only want to show the first role in the array. However, WordPress currently allows multiple roles per user, which I assume is the reasoning behind $user->roles being an array.

    Justin Tadlock

    @greenshady

    WordPress God

    Can WP_User() have multiple id’s passed at once?

    No. It only accepts a single ID.

    I have this for getting the current user’s role.

    I got the functionality from user-edit.php in the core.

    function get_current_user_role () {
        global $current_user;
        get_currentuserinfo();
        $user_roles = $current_user->roles;
        $user_role = array_shift($user_roles);
        return $user_role;
    };

    @dbmartin

    Cheers for this; works perfect!

    well, i think the most simple way is:
    on a Templates of wordpress, you can call a Function called get_currentuserinfo(); you can see it on: http://codex.wordpress.org/Function_Reference/get_currentuserinfo
    that way:

    <?php global $current_user;
          get_currentuserinfo();
    
          echo 'Username: ' . $current_user->user_login . "\n";
          echo 'User email: ' . $current_user->user_email . "\n";
          echo 'User level: ' . $current_user->user_level . "\n";
          echo 'User first name: ' . $current_user->user_firstname . "\n";
          echo 'User last name: ' . $current_user->user_lastname . "\n";
          echo 'User display name: ' . $current_user->display_name . "\n";
          echo 'User ID: ' . $current_user->ID . "\n";
    ?>

    here you can see the id, or the user name.
    the user level indicates the role of that user have like u see on:

    http://codex.wordpress.org/Roles_and_Capabilities#Role_to_User_Level_Conversion
    that way:

    User Level 0 converts to Subscriber Role
    User Level 1 converts to Contributor Role
    User Level 2 converts to Author Role
    User Level 3 converts to Author Role
    User Level 4 converts to Author Role
    User Level 5 converts to Editor Role
    User Level 6 converts to Editor Role
    User Level 7 converts to Editor Role
    User Level 8 converts to Administrator Role
    User Level 9 converts to Administrator Role
    User Level 10 converts to Administrator Role

    Justin Tadlock

    @greenshady

    WordPress God

    @jesus gonzalez

    You’re making the assumption that everyone uses the default WP roles along with the default WP capabilities for those roles.

    While it may work for some sites, the solution itself is essentially incorrect.

    You should pass your user ID into this code:

    $user = new WP_User( $user_id );
    
    if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    	foreach ( $user->roles as $role )
    		echo $role;
    }

    Justin you’re a life saver… Not only I’m using the Members plugin, your login, register, profile page templates ( although with Thematic ) but now this to?

    I mean… why isn’t this in the Codex?

    Heck, I just subscribed to themehybrid just to say thanks. It’s the least I can do!

    dbmartin, used your method, works a treat – thanks

Viewing 15 replies - 1 through 15 (of 19 total)
  • The topic ‘[Resolved] Get a user’s role by user ID’ is closed to new replies.
Skip to toolbar