• Resolved Justin Tadlock

    (@greenshady)


    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 4 replies - 16 through 19 (of 19 total)
  • 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') );

    Zeal

    (@zealwebdrumbeatcom)

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

    @zeal: roles do not apply to guest users.

    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;
    }
Viewing 4 replies - 16 through 19 (of 19 total)
  • The topic ‘Get a user’s role by user ID’ is closed to new replies.