Wordpress Role Display Name

守給你的承諾、 提交于 2019-12-18 04:57:12

问题


I am looking for a neat way to get the Wordpress role display name.

When you add the role (e.g. add_role( 'special', 'A Special Role'); ), you get to set a display name.

When you get the role (e.g. get_role( 'special' ); ) the role object returned simply has the name and the capabilities object.

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

And no display name. The display name is used all over the WP Admin back-end (users.php and user-edit.php), but it's a rabbit warren ... and I haven't been able to find a function that will return it. You can readily see it in the wp_user_roles row in the wp-options table - surely I don't need to go there?


回答1:


If you are running a non-english WordPress site and want to display the proper (translated) Role name, as it appears in all WordPress administration pages, here's how to do it:

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

where $role is the role name (i.e. 'special' in the original question).

Note: translate_user_role is a WordPress core not-so-documented function.




回答2:


Here is my solution to the above scenario:

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

Or in my case, what I was trying to achieve was:

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

Hope this helps someone




回答3:


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


来源:https://stackoverflow.com/questions/25059638/wordpress-role-display-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!