0
<?php global $current_user; echo array_shift($current_user->roles);>

Using this i can display user role slug but i want to display Name of the role. Any suggestion ? Thanks

  • echo $current_user->display_name; ? – RiddleMeThis Mar 10 at 14:59
  • @RiddleMeThis that would display the display name of the user, e.g. for tomjn it would be "Tom J Nowell". The OP doesn't want that though, they have admin and want "Administrator" – Tom J Nowell Mar 10 at 15:00
  • right. I totally misread the question. – RiddleMeThis Mar 10 at 15:07
2

WordPress does not (currently) have a global function (e.g. get_role_name()) for getting the role name (e.g. Shop Manager for shop-manager or maybe shop_manager etc.), but you can easily get (and then display) it like so:

$role = 'shop-manager'; // the role slug; it's up to you how to get the value..

$role_name = $role ? wp_roles()->get_names()[ $role ] : '';
/* Or directly access WP_Roles::$role_names:
$role_name = $role ? wp_roles()->role_names[ $role ] : '';
*/

echo $role_name;

References: wp_roles() and the WP_Roles class.

Some Additional Notes

  1. Be careful when using array_shift() - it does return the value but also removes the original item from the source array, so in your case, the next time you access $current_user->roles, it would be empty or no longer contains the user's role.

  2. Just as with the current post where it's a better practice to access the post object/data using get_post(), it's also recommended to use wp_get_current_user() to get the current user object/data instead of relying upon the global $current_user variable.

    And if your code runs only if the current user is authenticated/logged-in, then a shortcut for getting the user role is $role = wp_get_current_user()->roles[0]; :)

PS: Big thanks to @WacławJacek for his helpful comment! =)

| improve this answer | |
  • 1
    Be careful when using array_shift() though - it does return the value but also removes it from the source array. You can use $current_user->roles[0] instead. You can also use wp_get_current_user() instead of using the global variable. – Wacław Jacek Mar 10 at 15:15
1
<?php
global $current_user;
$role = $current_user->roles[0];
$role_name = $role ? wp_roles()->get_names()[ $role ] : '';
echo $role_name;
?>

Works like a charm

| improve this answer | |
  • It's quite bizarre that you unaccepted my answer after it's accepted for over a month - is my answer no longer working?... But anyway, thanks for your previous support. – Sally CJ Apr 22 at 22:40
  • 1
    sorry :) your answer helped – g3ar Apr 23 at 10:01

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.