我认为有两种方法可以做到这一点,两者都非常相似。
A) 您可以收集数组中显示的帖子的ID,然后排除具有post__not_in
类似这样的查询参数:
$years_loop = get_terms(
array(
\'taxonomy\' => \'works_year\',
\'orderby\' => \'slug\',
\'order\' => \'DESC\',
)
);
// array for displayed posts, we will update it with every loop
$displayed = [];
foreach($years_loop as $year_loop_slug) :
$args = array(
\'post_type\' => \'works\',
\'posts_per_page\' => -1,
\'post__not_in\' => array_unique( $displayed ),
\'tax_query\' => array(
array(
\'taxonomy\' => \'works_year\',
\'field\' => \'slug\',
\'terms\' => array( $year_loop_slug->slug ),
\'operator\' => \'IN\',
)
),
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
// update array with currently displayed post ID
$displayed[] = get_the_ID();
//your output
endwhile;
endforeach;
B)如果您想避免使用
post__not_in
参数,这可能会对站点性能产生不良影响,您可以检查循环中的重复项:
$years_loop = get_terms(
array(
\'taxonomy\' => \'works_year\',
\'orderby\' => \'slug\',
\'order\' => \'DESC\',
)
);
// array for displayed posts, we will update it with every loop
$displayed = [];
foreach($years_loop as $year_loop_slug) :
$args = array(
\'post_type\' => \'works\',
\'posts_per_page\' => -1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'works_year\',
\'field\' => \'slug\',
\'terms\' => array( $year_loop_slug->slug ),
\'operator\' => \'IN\',
)
),
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
// if the current post was already displayed, move on to the next iteration of this loop
if ( in_array( get_the_ID(), $displayed ) ){
continue;
}
// update array with currently displayed post ID
$displayed[] = get_the_ID();
//your output
endwhile;
endforeach;
代码未经测试,但您已经明白了。