WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get a user's role by user ID (20 posts)

  1. Justin Tadlock
    Member
    Posted 4 years ago #

    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?

  2. MichaelH
    Member
    Posted 4 years ago #

    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>';
        }
      }
    }
    ?>
  3. Justin Tadlock
    Member
    Posted 4 years ago #

    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.

  4. Justin Tadlock
    Member
    Posted 4 years ago #

    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;
    ?>
  5. NotAlame
    Member
    Posted 4 years ago #

    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?

  6. NotAlame
    Member
    Posted 4 years ago #

    @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??

  7. Justin Tadlock
    Member
    Posted 4 years ago #

    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.

  8. kunaimedia
    Member
    Posted 4 years ago #

    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?

  9. Justin Tadlock
    Member
    Posted 4 years ago #

    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.

  10. Justin Tadlock
    Member
    Posted 4 years ago #

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

    No. It only accepts a single ID.

  11. darrinb
    Member
    Posted 4 years ago #

    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;
    };
  12. Casemon
    Member
    Posted 4 years ago #

    @dbmartin

    Cheers for this; works perfect!

  13. Jesus gonzalez
    Member
    Posted 4 years ago #

    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

  14. Justin Tadlock
    Member
    Posted 4 years ago #

    @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;
    }
  15. sareiodata
    Member
    Posted 4 years ago #

    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!

  16. frankfisher
    Member
    Posted 4 years ago #

    dbmartin, used your method, works a treat - thanks

  17. Francis Crossen
    Member
    Posted 4 years ago #

    As greenshady says the only gotcha you need to watch out for is that $roles is an array and if you have a user assigned to more than one role you will only get one returned to you.
    I am coding a plugin which cannot assume a single role per user.
    I recently used the following to address the problem:

    function tina_mvc_user_has_role( $roles_to_check=array() ) {
    
      if( ! $roles_to_check ) return FALSE;
    
      global $current_user;
      get_currentuserinfo();
      $user_id = intval( $current_user->ID );
    
      if( ! $user_id ) {
        return FALSE;
      }
      $user = new WP_User( $user_id ); // $user->roles
    
      return in_array( $roles_to_check, $user->roles, FALSE );
    
    }

    Example:
    $user_role_exists = tina_mvc_user_has_role( array('Subscriber','MyRole') );

  18. Zeal Murapa
    Member
    Posted 4 years ago #

    how do I list users and their roles for the guest?

  19. Francis Crossen
    Member
    Posted 4 years ago #

    @zeal: roles do not apply to guest users.

  20. Ben Dunkle
    Member
    Posted 3 years ago #

    Thanks greenshady, this code is very handy.
    Also, if you don't want to hard-code the user's id, you can use this:

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags