在 WooCommerce 中的“我的帐户”仪表板上显示用户角色名称

Display User Role Name on My Account Dashboard in WooCommerce

我为此尝试了各种解决方案,虽然下面的代码有效并且不会在日志中产生任何错误或类似的东西,但我正在努力理解如何获取用户角色的名称而不是实际的帐户用户名。

这是我使用的代码:

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>';

我想要这样显示:

Username: 用户名 Account type:角色名称

用户名和帐户类型应分两行。 账户类型的重点是因为我添加了这个:

add_role ( 'business', __( 'Business', 'woocommerce' ), array( 'read' => true, ));

根据您的自定义角色尝试以下操作 "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 />';
}

它应该如你所愿。


从用户角色 slug 获取角色名称:

global $wp_roles;

$role = 'business';
$role_name = $wp_roles->roles[$role]['name'];

如果每个用户都有一个唯一的用户角色,您可以使用以下内容:

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 />';
}

或者您可以通过以下方式获取最后一个用户角色:

$role_name = $wp_roles->roles[end($current_user->roles)]['name'];