【问题标题】:Display User Role Name on My Account Dashboard in WooCommerce在 WooCommerce 的我的帐户仪表板上显示用户角色名称
【发布时间】:2019-10-05 10:38:02
【问题描述】:

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

这是我正在使用的代码:

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, ));

【问题讨论】:

    标签: php wordpress woocommerce account user-roles


    【解决方案1】:

    根据您的自定义角色“业务”尝试以下操作:

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

    【讨论】:

    • 效果很好。但是我有 6 种不同类型的角色,我需要代码从系统中“获取角色”。如果我必须手动添加所有角色,那么在添加/删除角色时会变得很繁琐。抱歉,我最初的问题没有说得更清楚。
    • @JonnyKapula 我已经添加了关于角色名称的添加... 注意:不要忘记一个用户可以有多个角色,所以如果在使用add_role() 时,它会在现有用户角色中添加一个角色数组。
    • 谢谢,但这也无济于事。我仍然需要自己定义角色,而不是系统获取它。
    • @JonnyKapula 如果用户只有一个唯一的用户角色,系统只能自动获取用户角色名称。我在最后的答案中添加了一个补充。
    • 是的,在我的情况下,所有角色都被删除(管理员除外)并添加了所需的角色。
    猜你喜欢
    • 2022-11-24
    • 2017-05-24
    • 2020-10-30
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多