Im trying to do something which I feel should be quite easy but I can't seem to quite grasp. I have the below code which echo's users roles. Great. Fantastic. BUT I have a problem when a user is assigned to multiple roles. It returns null. Can someone please help me?


global $wp_roles;
$user_role = implode(', ', get_userdata($user->ID)->roles);  
echo($wp_roles->role_names[ $user_role ]);

1 Answer 1


I assume you need a foreach loop and echo each roles name separately. Here's how to do it:

global $wp_roles;
$user_role = get_userdata($user->ID)->roles;

// Check if there is any role for this user
if( $user_role ) {
    foreach ( $user_role as $key => $role ) {
        echo $wp_roles->role_names[ $role ];
        // Add a seperator except for the last name
        if ( count ( $user_role ) != ( $key + 1 ) ) { echo '/'; }
  • Thats great! Thanks. I wonder if you could help with a follow up? If the user has more than 1 role, how do I include ' / ' as a separator?
    – LB79
    Commented Mar 4, 2018 at 22:49
  • You're welcome! I've updated the answer for you.
    – Johansson
    Commented Mar 4, 2018 at 23:33
  • Awesome! Just 1 more ask if I may? How can I exclude the final / from the end? Thanks
    – LB79
    Commented Mar 5, 2018 at 21:32
  • But it already does that. I've tried the code and it doesn't print / after the last role.
    – Johansson
    Commented Mar 5, 2018 at 21:46
  • I thought it was odd that you wouldn't have accounted for that. After your post just now Ive been scratching me head and after clearing my cache (for some reason) its working as you intended. Many thanks again for your help - You're a star!
    – LB79
    Commented Mar 5, 2018 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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