php 通过 ID WordPress 获取用户角色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36720949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get user role by ID WordPress
提问by Tristan .L
I need to somehow check someone's role with only their id.
I have found the current_user_can()
check. But this only works for people that are logged in. How would I check for this if that user isn't the current user? I am using a phone order system but that uses the admin/specific account to order for other people.
我需要以某种方式仅使用他们的 id 来检查某人的角色。我找到了current_user_can()
支票。但这仅适用于登录的人。如果该用户不是当前用户,我将如何检查?我正在使用电话订购系统,但它使用管理员/特定帐户为其他人订购。
回答by Meathanjay
You can't get user role directly. First, you have to get the user_meta_data, and it will return an Object that will contain user roles.
您无法直接获取用户角色。首先,您必须获得 user_meta_data,它会返回一个包含用户角色的对象。
Code:
代码:
$user_meta=get_userdata($user_id);
$user_roles=$user_meta->roles; //array of roles the user is part of.
回答by Ahmad Awais
The info you need to know before you proceed:
在继续之前您需要了解的信息:
- You can't get user role by ID directly.
- You canget all the roles a user is assigned to.
- 您不能直接通过 ID 获取用户角色。
- 你可以得到一个用户被分配到的所有角色。
Let's get all the roles and check if the role you're interested in is there or now.
让我们获取所有角色并检查您感兴趣的角色是否存在或现在。
<?php
// Get the user object.
$user = get_userdata( $user_id );
// Get all the user roles as an array.
$user_roles = $user->roles;
// Check if the role you're interested in, is present in the array.
if ( in_array( 'subscriber', $user_roles, true ) ) {
// Do something.
echo 'YES, User is a subscriber';
}
回答by Wessam Mohsen
$user_meta = get_userdata($user_id);
$user_roles = $user_meta->roles;
if ( in_array( 'administrator', $user_roles, true ) ) {
//echo User is a administrator';
}
回答by LordOfWebDev
hello try this optimal code
你好试试这个最佳代码
if (get_userdata($post->post_author)->roles[0] == 'your_specified_role'){
echo 'role exist';
}else{
echo 'role does not exist';
}