WordPress 角色显示名称

10

我正在寻找一种简洁的方法来获取WordPress角色的显示名称。

当你添加角色(例如add_role('special','A Special Role');)时,你可以设置一个显示名称。

当你获取角色(例如get_role('special');)时,返回的角色对象只有名称和能力对象。

WP_Role Object(
[name] => special
[capabilities] => Array() )

而且没有显示名称。显示名称在 WP 管理后端 (users.php 和 user-edit.php) 到处使用,但这是一个兔子洞... 我找不到一个能返回它的函数。您可以在wp-options表中的wp_user_roles行中轻松看到它 - 我肯定不需要去那里吧?

3个回答

12

如果您正在运行一个非英语的WordPress站点,并希望显示在所有WordPress管理页面中出现的正确(翻译后的)角色名称,以下是如何实现:

    global $wp_roles;
    echo translate_user_role( $wp_roles->roles[ $role ]['name'] );

其中$role代表角色名称(例如在原问题中为'special')。

注意:translate_user_role是WordPress核心功能之一,文档不够详尽。


6

以下是我对上述情景的解决方案:

    global $wp_roles;
    $role = $wp_roles->roles['special']['name'];

在我的情况下,我想要实现的是:

    global $wp_roles;
    $u = get_userdata($user->ID);
    $role = array_shift($u->roles);
    $user->role = $wp_roles->roles[$role]['name'];

希望这能帮助到有需要的人。

-2

<?php
$user_roles = $current_user->roles;
$user_role = array_shift($user_roles);

if ($user_role == 'administrator') {
echo 'Administrator';
} elseif ($user_role == 'editor') {
echo 'Editor';
} elseif ($user_role == 'author') {
echo 'Author';
} elseif ($user_role == 'contributor') {
echo 'Contributor';
} elseif ($user_role == 'subscriber') {
echo 'Subscriber';
} else {
echo '<strong>' . $user_role . '</strong>';
}
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接