我有以下WP_Query论点:
$posts = new WP_Query(array(
'post__in' => $postids,
'meta_key' =>'ratings_average',
'orderby'=>'meta_value_num',
'order' =>'DESC',
));
Run Code Online (Sandbox Code Playgroud)
$ postids是一个从另一个中检索的id数组WP_Query.我的问题是,即使$ postids为空,Wordpress循环显示帖子.如果$ postids为空,我如何管理它不应该显示任何帖子.
这不是直接解决问题,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..
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,WP_Query只有在其中$postids包含值/ s时才会发生调用.如果没有,则不会进行调用WP_Query,循环将永远不会发生,就像您的查询返回0个帖子一样.
小智 5
使用 WP_Query 保持流程正确。像这样使用它:
$postIdArray = array(
1, 2, 3
);
$queryArgs = array(
'post_type' => 'any',
'post_status' => 'published',
'post__in' => ((!isset($postIdArray) || empty($postIdArray)) ? array(-1) : $postIdArray)
);
Run Code Online (Sandbox Code Playgroud)
这样,您仍然可以针对 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;
Run Code Online (Sandbox Code Playgroud)
如前所述,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',
));
Run Code Online (Sandbox Code Playgroud)
你说不好的做法?是的,我不确定是从谁那边...
| 归档时间: |
|
| 查看次数: |
5690 次 |
| 最近记录: |