简体   繁体   English

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

[英]Display User Role Name on My Account Dashboard in WooCommerce

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 Username:Username:用户名Account type:角色名称

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM