How to get the currently logged in user's role in wordpress?
Upon activation, you'll have a new menu item called 'Members' in your WordPress admin panel. You need to go to Members » Roles and then click on the user role you want to edit. In this example, we will be editing the 'Author' role, but you can choose the best role for your needs.
is_user_logged_in(): bool. Determines whether the current visitor is a logged in user.
To check if the currently logged in user is an administrator, use the current_user_can function. To check if a user is an administrator, you can specify the capability as an argument of current_user_can function (e.g. manage_options).
Assuming you have the user id ($user_id) something like this should work:
$user = new WP_User( $user_id );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role )
echo $role;
}
Get the user id from your session.
If you don't know the user id, this function will help you (put it in your theme functions.php file)
function get_user_role() {
global $current_user;
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);
return $user_role;
}
And then, in your template you can get user role by calling get_user_role().
Found it here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With