我正在尝试更改页面的查询,其中post meta值为_members_access_role
不符合当前登录用户的要求。以下是我目前掌握的情况:
// Get all posts with the access level of \'Member\'
function members_get_member_posts() {
$post_ids = array();
$args=array(
\'post_type\' => array(\'post\',\'tribe_events\',\'document\'),
\'meta_key\' => \'_members_access_role\',
\'meta_value\' => \'member\',
\'post_status\' => array(\'publish\',\'private\')
);
$protected_posts = get_posts($args);
if($protected_posts) {
foreach($protected_posts as $p) {
$post_ids[] = $p->ID;
}
}
// return an array of paid post IDs
return $post_ids;
}
// Hide all posts from users who are not logged-in or are not administrators or members
function members_hide_member_posts($query) {
$current_user = wp_get_current_user();
if(empty($current_user) || ($current_user->roles[0] != \'member\' && $current_user->roles[0] != \'administrator\') && (false == $query->query_vars[\'suppress_filters\'])) {
$protected_posts = members_get_member_posts();
if($protected_posts)
$query->set(\'post__not_in\', $protected_posts);
}
return $query;
}
add_filter(\'pre_get_posts\', \'members_hide_member_posts\');
如果我快点
print_r(members_get_member_posts())
我正确地看到了post id的数组,但在前端,post仍然显示在不应该显示的位置(因为我正在将返回的函数值输入到
posts__not_in
).
例如,如果公共用户访问该站点,他们仍然可以看到成员(角色)帖子。也有点麻烦global $current_user
对象--因为它不会检查$current_user->ID
是否为空,页面是否会产生关于内存限制的致命错误(即使在我将php.ini文件设置为256M之后),那么可能是内存泄漏?谢谢
更新虽然没有文档记录,但我仔细检查了您是否可以使用array()
的值post_type
在截至3.3的get\\U帖子中(我相信)。也尝试不使用它,只返回应该返回的帖子-因此数据正在返回,而不是“过滤”该数据。
最合适的回答,由SO网友:Pippin 整理而成
Try this version:
// Get all posts with the access level of \'Member\'
function members_get_member_posts() {
$post_ids = wp_cache_get( \'wpse61487_members_posts\' );
if ( false === $post_ids ) {
$post_ids = array();
$args=array(
\'post_type\' => \'any\',
\'meta_key\' => \'_members_access_role\',
\'meta_value\' => \'member\',
\'post_status\' => array(\'publish\',\'private\')
);
$protected_posts = get_posts($args);
if($protected_posts) {
$post_ids = wp_list_pluck( $protected_posts, \'ID\' );
}
wp_cache_set( \'wpse61487_members_posts\', $post_ids );
}
// return an array of paid post IDs
return $post_ids;
}
// Hide all posts from users who are not logged-in or are not administrators or members
function members_hide_member_posts($query) {
if( !$query->is_main_query() )
return;
$current_user = wp_get_current_user();
if(empty($current_user) || ($current_user->roles[0] != \'member\' && $current_user->roles[0] != \'administrator\') && (false === $query->query_vars[\'suppress_filters\'])) {
$protected_posts = members_get_member_posts();
if( !empty( $protected_posts ) )
$query->set(\'post__not_in\', $protected_posts);
}
}
add_action(\'pre_get_posts\', \'members_hide_member_posts\');