<?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 Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.Sign up to join this community
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;
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
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; :)
PS: Big thanks to @WacławJacek for his helpful comment! =)