Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何获取当前登录的用户';她在wordpress中的角色?_Php_Wordpress - Fatal编程技术网

Php 如何获取当前登录的用户';她在wordpress中的角色?

Php 如何获取当前登录的用户';她在wordpress中的角色?,php,wordpress,Php,Wordpress,如何在wordpress中获取当前登录用户的角色?假设您有用户id($user\u id),类似这样的操作应该可以: $user = new WP_User( $user_id ); if ( !empty( $user->roles ) && is_array( $user->roles ) ) { foreach ( $user->roles as $role ) echo $role; } 从会话中获取用户id。如果您不知道用户

如何在wordpress中获取当前登录用户的角色?

假设您有用户id($user\u id),类似这样的操作应该可以:

$user = new WP_User( $user_id );

if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
    foreach ( $user->roles as $role )
        echo $role;
}

从会话中获取用户id。

如果您不知道用户id,此函数将帮助您(将其放入theme functions.php文件中)

然后,在模板中,可以通过调用get_user_role()来获取用户角色


找到它。

如果我在一个用户中添加了两个或更多角色,则此方法不适用,原因是它只返回添加到用户的单个或第一个角色,使用数组\u shift PHP函数进行移位。请注意,
$current\u user
始终存在,默认情况下由空属性填充,因此,尽管这段代码看起来会出现对象访问和索引问题,但它实际上是有效的。新访问者返回的角色将为
NULL
function get_user_role() {
    global $current_user;

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

    return $user_role;
}
function get_role_by_id( $id ) {

    if ( !is_user_logged_in() ) { return false; }

    $oUser = get_user_by( 'id', $id );
    $aUser = get_object_vars( $oUser );
    $sRole = $aUser['roles'][0];
    return $sRole;

}