I have tried various solutions for this and while the code below works and do not generate any errors in the log or anything like that, I am struggling with understanding how to get the name of the user role and not the actual account username.
Here's the code I am using:
global $current_user;
wp_get_current_user();
if ( is_user_logged_in()) {
echo 'Username: ' . $current_user->user_login .'';
echo '<br />';
echo 'User display name: ' . $current_user->display_name .'';
}
else { wp_loginout(); }
echo '<br>';
I want it to display like this:
Username:
username
Account type:
name of role
The username and account type should be on two separate rows. The point of the account type is because I added this:
add_role ( 'business', __( 'Business', 'woocommerce' ), array( 'read' => true, ));
Try the following based on your custom role "business":
global $current_user;
if ( $current_user > 0 ) {
echo __('Username:') . ' ' . $current_user->user_login . '<br />';
$account_type = in_array('business', $current_user->roles) ? __('Business') : __('Customer');
echo __('Account type') . ' ' . $account_type . '<br />';
}
It should work as you wish.
To get the role name from a user role slug:
global $wp_roles;
$role = 'business';
$role_name = $wp_roles->roles[$role]['name'];
If each user has a unique user role, you can use the following:
global $current_user, $wp_roles;
if ( $current_user > 0 ) {
$role_name = $wp_roles->roles[reset($current_user->roles)]['name'];
echo __('Username:') . ' ' . $current_user->user_login . '<br />';
echo __('Account type') . ' ' . $role_name . '<br />';
}
Or you can get the last user role with:
$role_name = $wp_roles->roles[end($current_user->roles)]['name'];