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
-
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. -
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 usewp_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! =)