IMO最好的方法是根据集合统计每页返回的帖子posts_per_page
在查询中设置选项。如果计数小于集合posts_per_page
, 计算差额,然后将其用作在自定义查询中填充其余内容的帖子数量
这就是它的工作原理:
首先,计算“main”查询返回的帖子数量,在这种情况下,这将是
$related_posts_args->posts
count($related_posts_args->posts)
因为您已经设置了
posts_per_page
到
10
, 这将是用来检查计数的数字。
count($related_posts_args->posts) < 10
如果计数小于10,则需要获得10和计数之间的差值。这种差异将是
posts_per_page
自定义查询选项
$ppp = 10 - count($related_posts_args->posts);
您现在可以运行自定义查询来检索帖子以填充空白。您只需要添加自己的查询参数
这是完整的代码
if( count($related_posts_args->posts) < 10 ) {
$ppp = 10 - count($related_posts_args->posts);
$args = [ //Add your own query arguments to suite your needs
\'orderby\' => \'rand\',
\'posts_per_page\' => $ppp
];
$q = new WP_Query( $args );
if( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
//Display your loop elements
}
wp_reset_postdata();
}
}
与您的代码集成
$related_posts_args = [
\'tag__and\' => $list_of_tags, // array of tag IDS
\'posts_per_page\' => 10,
\'post__not_in\' => $already_posted, // array of post IDs
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'orderby\' => \'rand\',
];
$related_posts_query = new WP_Query( $related_posts_args );
if ( $related_posts_query->have_posts() ) {
while ( $related_posts_query->have_posts() ) {
$related_posts_query->the_post();
//Display your loop elements
}
wp_reset_postdata();
if( count($related_posts_args->posts) < 10 ) {
$ppp = 10 - count($related_posts_args->posts);
$args = [ //Add your own query arguments to suite your needs
\'orderby\' => \'rand\',
\'posts_per_page\' => $ppp
];
$q = new WP_Query( $args );
if( $q->have_posts() ) {
while( $q->have_posts() ) {
$q->the_post();
//Display your loop elements
}
wp_reset_postdata();
}
}
}