Php WordPress:如果用户在数组中
我试图找出当前用户是否在允许列表中,如果是,让他们查看页面。如果没有,那么拒绝他们的页面。因为用户可能处于两个用户级别,所以我将它们添加到一个数组中,然后对照允许的用户数组进行检查 这是我在page.php文件中使用的代码:Php WordPress:如果用户在数组中,php,arrays,wordpress,Php,Arrays,Wordpress,我试图找出当前用户是否在允许列表中,如果是,让他们查看页面。如果没有,那么拒绝他们的页面。因为用户可能处于两个用户级别,所以我将它们添加到一个数组中,然后对照允许的用户数组进行检查 这是我在page.php文件中使用的代码: // Check the category and whether it is a child of 5 foreach((get_the_category()) as $childcat) { if (cat_is_ancestor_of(5, $childcat))
// Check the category and whether it is a child of 5
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(5, $childcat)) {
// define arrays
$inRoles = array();
$allowedToAccess = array('administrator','gold','pmpro_role_4');
// Check if user is logged in and get role
if ( is_user_logged_in() ) {
$user = new WP_User( $user_ID );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role ) {
// Add current roles to their roles array
array_push($inRoles, $role);
var_dump($inRoles);
// check if role(s) is/are allowed
if (in_array($inRoles, $allowedToAccess)) {
echo "Yes, You are ALLOWED TO ACCESS THIS PAGE";
} else {
echo "Nope, you can not access this page";
}
}
}
}
}
}
您可以在那里看到的var\u dump
输出以下内容:
array(1) { [0]=> string(13) "administrator" }
因此,正如您所看到的,用户是管理员。但是,由于某些原因,页面上的输出为:
不,您无法访问此页面
有人知道为什么吗?试试这个
// Check the category and whether it is a child of 5
foreach((get_the_category()) as $childcat) {
if (cat_is_ancestor_of(5, $childcat)) {
// define arrays
$inRoles = array();
$allowedToAccess = array('administrator','gold','pmpro_role_4');
// Check if user is logged in and get role
if ( is_user_logged_in() ) {
$user = new WP_User( $user_ID );
if ( !empty( $user->roles ) && is_array( $user->roles ) ) {
foreach ( $user->roles as $role => $name ) {
// Add current roles to their roles array
array_push($inRoles, $name);
var_dump($inRoles);
// check if role(s) is/are allowed
if(in_array($inRoles[0],$allowedToAccess))
{
echo "Yes, You are ALLOWED TO ACCESS THIS PAGE";
}
else
{
echo "Nope, you can not access this page";
}
}
}
}
}
}
@用户3596752:你能给我看看印刷品吗。这是由我的代码生成的:Array([0]=>administrator)@user3596752:现在试试这个again@user3596752:如果您不想使用数组_intersect,请使用此if(在_数组中($inRoles[0],$allowedToAccess)){}是的,您可以!非常感谢。