【发布时间】:2018-12-19 06:53:43
【问题描述】:
我有两个自定义视图字段。 weekly_views 和 all_views。每周视图自定义字段每周都会被删除,并从 0 开始再次计算视图。所以现在我想要实现的是按每周视图显示 12 个帖子,但是当自定义字段被删除时,除非这些帖子有视图,否则查询不会显示任何内容.我想在这里显示all_views 的帖子,而不是没有帖子。
我的查询如下,但它没有按我的意愿工作。简而言之,我想要实现的是通过weekly_views 自定义字段显示帖子,但如果没有帖子,则通过all_views 显示帖子。此外,如果 weekly_views 的帖子少于 12 个,则先显示 weekly_views 的帖子,然后再显示 all_views 的剩余帖子。
$args = array(
'post_type' => array( 'custom_post_type_1', 'custom_post_type_2'),
'posts_per_page' => '12',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'weekly_views',
),
array(
'key' => 'all_views',
),
),
);
上面的代码返回了我的帖子,但按 all_views 排序。
编辑
对我有用的新查询
<?php
$args = array(
'post_type'=> array( 'custom_post_type1', 'custom_post_type2'),
'posts_per_page' => '12',
'meta_key' => 'weekly_views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
);
$the_query = new WP_Query( $args );
if ($the_query->post_count < 12) {
$countweeklyposts = $the_query->post_count;
$showallpostscount = 12 - $countweeklyposts;
$args2 = array(
'post_type'=> array( 'band', 'artist'),
'posts_per_page' => $showallpostscount,
'meta_key' => 'all_views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
);
$the_query2 = new WP_Query( $args2 );
}
?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
//Code to show posts goes here
<?php
endwhile;
wp_reset_postdata();
?>
<?php while ($the_query2 -> have_posts()) : $the_query2 -> the_post(); ?>
//Code to show posts goes here
<?php
endwhile;
wp_reset_postdata();
?>
【问题讨论】: