我想禁止没有权限查看这些帖子的用户访问后端/管理员中的帖子。此功能类似于作者角色,但此“权限”由ACF 用户关系字段,而不是WP核心角色或权限。
更为复杂的是,用户关系字段实际上指向一个父/分组自定义帖子类型,然后该类型与我试图筛选的子帖子元素相关联。因此,它不仅显示用户编写的帖子,还显示其他人编写的帖子,但他们已被授予管理权限。让我在下面解释一下。。。
自定义帖子类型:Shoes [shoe
]
自定义帖子类型:Brands [brand
]
假设你有一双名为“Air Jordans”的“鞋”,还有一个名为“Nike”的“品牌”因此您创建了ACF bidirectional relationship 介于“Air Jordan”和“Nike”之间现在,假设您在网站上创建了一个用户,您希望能够编辑所有“Nike”鞋因此,您可以在“品牌”帖子类型中创建一个ACF用户关系字段类型,并可以将多个用户分配给该品牌的管理员因此,当该用户登录到后端并查看所有鞋款时,我只想显示Nikes鞋款,他们将能够编辑所有Nike鞋款我已经建立了在前端处理此问题的逻辑,它工作得非常完美,现在我想在后端复制此逻辑,以便在那里进行过滤。以下是我在前端构建的内容供参考:
$current_user = wp_get_current_user();
/* Get All Brands the Current User can Administer */
$brands_admin_args = array(
\'post_type\' => \'brand\',
\'meta_query\' => array(
array(
\'key\' => \'admins\', // This is my ACF User field that tracks brand admins.
\'value\' => \'"\' . $current_user->ID . \'"\',
\'compare\' => \'LIKE\'
),
),
);
$brands_admin = get_posts($brands_admin_args);
/* Get All Shoes The User Can Administer Based On Each Brand They Can Administer*/
$approved_shoes_args = array(
\'post_type\' => \'shoe\',
\'meta_query\' => array(
\'relation\' => \'OR\'
),
);
foreach ($brands_admin as $ba) {
array_push($approved_shoes_args[\'meta_query\'], array(
\'key\' => \'shoe_brands\', // This is my ACF Relationship field between Shoes and Brands
\'value\' => \'"\' . $ba->ID . \'"\',
\'compare\' => \'LIKE\'
));
}
$approved_shoes = new WP_Query($approved_shoes_args);
SO网友:Mike B.
采纳@Welcher的使用建议pre_get_posts
, 我使用现有代码并编译以下内容以进行筛选编辑。基于授予当前用户访问权限的ACF字段的自定义帖子的php页面:
add_action( \'pre_get_posts\', \'customize_products_for_admins\' );
function customize_products_for_admins( $wp_query ) {
if ( is_admin() && $wp_query->is_main_query() && current_user_can(\'editor\') ) { // I know I need more conditional statements here
$current_user = wp_get_current_user();
/* Get All Brands the Current User can Administer */
$brands_admin_args = array(
\'post_type\' => "brand",
\'meta_query\' => array(
array(
\'key\' => "admins",
\'value\' => \'"\' . $current_user->ID . \'"\',
\'compare\' => "LIKE"
),
),
);
$brands_admin = get_posts($brands_admin_args);
/* Get All Shoes The User Can Administer Based On Each Brand They Can Administer */
$approved_shoes_args = array(
\'meta_query\' => array(
\'relation\' => "OR"
),
);
foreach ($brands_admin as $ba) {
array_push($approved_shoes_args[\'meta_query\'], array(
\'key\' => "shoe_brands", // This is my ACF Relationship field between Shoes and Brands
\'value\' => \'"\' . $ba->ID . \'"\',
\'compare\' => "LIKE"
));
}
$wp_query->set(\'meta_query\', $approved_shoes_args);
}
}