0

I'm using the PHP code seen at the bottom of this post to get the user's role from user ID. It works, but fails if the user role has been changed after registering. I've been looking for ages trying to find out how WordPress changes roles and why this would cause the below code to not work but am now lost.

Update: The error I get is

Warning: array_key_exists() expects parameter 2 to be array

$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;
  • I've tried your code, changing the user role several times to different roles, newly registered user too, it does work perfectly fine for me. – Nicolai Sep 19 '14 at 18:30
2

You can simply use WP_User class.

$user = new WP_User( $user_id );

    foreach( $user->roles as $role ) {
     $role = get_role( $role );
     if ( $role != null )
      echo $role->name;
    }

Read more about WP_User

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.