<?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
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.
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 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! =)
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.
Commented
Mar 10, 2020 at 15:15
<?php
global $current_user;
$role = $current_user->roles[0];
$role_name = $role ? wp_roles()->get_names()[ $role ] : '';
echo $role_name;
?>
Works like a charm
tomjn
it would be "Tom J Nowell". The OP doesn't want that though, they haveadmin
and want"Administrator"