How to get the Role Name of the current user? (WordPress)

I currently have this snippet:

$user = new WP_User(get_current_user_id()); 
echo $user->roles[1];

and the output the slug of the bbPress forum role.
(roles[0] would be the general WP role but I don’t need that.)

What I need is the role name, not the slug.
So, the expected output should be something like “Keymaster”, “Participant”, “Spectator” etc.

So, how do I get the Role Name of the current user?

5 Answers
5

I’m not sure if bbPress follows WordPress conventions, but WP has a global class called $WP-roles that holds the role information. So, starting from what you have, there is the role of the current user:

$current_role = $user->roles[1];

Next, retrieve a list of all roles:

$all_roles = $wp_roles->roles; 

Then, loop through $all_roles and find the $current_role":

foreach ($all_roles as $role_key => $role_details) {
  if ($role_key == $current_role) $current_role_name = $role_details['name'];
  }

Now, $current_role_name should hold the display name you’re looking for (I didn’t check this code, however).

Leave a Comment