我有以下WP_Query
个参数:
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
$ postids 是从另一个WP_Query
检索的ID数组。我的问题是,即使 $ postids 为空,Wordpress循环也会显示帖子。如果 $ postids 为空,我该如何管理它不应显示任何帖子。
答案 0 :(得分:9)
这不能直接解决post__in
的问题,但我不知道为什么这不起作用..
if(!empty($postids)){
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
} else {
//Do something else or nothing at all..
}
正如您所看到的那样WP_Query
调用仅在$postids
中包含值{s}时才会发生。如果它没有,则不会调用WP_Query
并且循环将永远不会发生,就像您的查询返回0个帖子一样。
答案 1 :(得分:4)
如上所述,wp开发人员并不想解决这个问题。话虽如此,您可以传递非空数组的无效ID,如下所示:
if(empty($postids)) {
$postids = ['issue#28099'];
}
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
你说不好的做法?是的,我不确定在哪一方......
答案 2 :(得分:2)
使用WP_Query保持流程正确。像这样使用它:
$postIdArray = array(
1, 2, 3
);
$queryArgs = array(
'post_type' => 'any',
'post_status' => 'published',
'post__in' => ((!isset($postIdArray) || empty($postIdArray)) ? array(-1) : $postIdArray)
);
这样您仍然可以针对WP_Query对象进行编码。
例如:
$postIdArray = array(
1, 2, 3
);
$queryArgs = array(
'post_type' => 'any',
'post_status' => 'published',
'post__in' => ((!isset($postIdArray) || empty($postIdArray)) ? array(-1) : $postIdArray)
);
$postQuery = new \WP_Query($queryArgs);
$postCount = $postQuery->post_count;
$totalCount = $postQuery->found_posts;
答案 3 :(得分:1)
也许你有一些粘贴帖子。在这种情况下,WordPress会将这些帖子添加到您的查询中。
解决方案是设置'ignore_sticky_posts' => 1
。将其应用于您的代码:
$posts = new WP_Query(array(
'post__in' => $postids,
'ignore_sticky_posts' => 1,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
答案 4 :(得分:0)
遇到同样的问题,最好的办法是检查数组是否为空,然后将无效的ID传递给它:
if(empty($postids)){
$postids[]= 0;
}
在查询和问题解决之前添加它。