WordPress如何通过WP_Query每4篇文章后插入4篇分类文章
WordPress文章穿插查询实现方案
关于是否需要两个独立查询
需要使用两个独立的WP_Query,但你当前编写的查询参数存在逻辑错误:分类法查询中不需要加offset => 4参数,该参数会直接跳过分类下前4篇文章,不符合穿插需求;另外你的常规文章查询没有排除指定分类的文章,会导致后续渲染时文章重复输出。
实现思路
- 第一个查询拉取所有不属于
the-community分类的常规news文章 - 第二个查询拉取所有归属
the-community分类的news文章 - 循环渲染时维护计数器,每输出4篇常规文章,就从分类文章结果中取4篇插入,所有常规文章渲染完成后如果还有剩余分类文章,统一输出在列表末尾
完整实现代码
第一步:初始化两个查询
// 查询常规新闻(排除the-community分类文章) $regular_news_args = array( 'post_type' => 'news', 'posts_per_page' => -1, 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'news-category', 'field' => 'slug', 'terms' => 'the-community', 'operator' => 'NOT IN', ), ), ); $regular_news = new WP_Query($regular_news_args); $regular_posts = $regular_news->posts; // 查询社区分类新闻 $community_news_args = array( 'post_type' => 'news', 'posts_per_page' => -1, 'post_status' => 'publish', 'tax_query' => array( array( 'taxonomy' => 'news-category', 'field' => 'slug', 'terms' => 'the-community', ), ), ); $community_news = new WP_Query($community_news_args); $community_posts = $community_news->posts; $community_index = 0; // 记录社区文章当前输出位置
第二步:循环渲染穿插逻辑
if ($regular_news->have_posts()) { $counter = 0; // 常规文章输出计数器 while ($regular_news->have_posts()) { $regular_news->the_post(); // 单篇常规文章渲染代码,可根据需求自定义结构 echo '<div class="news-item regular-news">'; the_title('<h3>', '</h3>'); the_excerpt(); echo '</div>'; $counter++; // 每输出4篇常规文章,插入4篇社区文章 if ($counter % 4 == 0 && !empty($community_posts)) { echo '<div class="community-news-group">'; $insert_count = 0; // 最多插入4篇,同时避免超出社区文章总数 while ($insert_count < 4 && $community_index < count($community_posts)) { $post = $community_posts[$community_index]; setup_postdata($post); // 单篇社区文章渲染代码,可根据需求自定义结构 echo '<div class="news-item community-news">'; the_title('<h4>', '</h4>'); the_excerpt(); echo '</div>'; $community_index++; $insert_count++; } wp_reset_postdata(); // 重置回常规查询的当前文章上下文 echo '</div>'; } } wp_reset_postdata(); // 常规文章输出完后如果还有剩余社区文章,全部输出在末尾 if ($community_index < count($community_posts)) { echo '<div class="community-news-group remaining">'; for ($i = $community_index; $i < count($community_posts); $i++) { $post = $community_posts[$i]; setup_postdata($post); echo '<div class="news-item community-news">'; the_title('<h4>', '</h4>'); the_excerpt(); echo '</div>'; } wp_reset_postdata(); echo '</div>'; } }
注意事项
如果文章列表需要分页,不能使用
posts_per_page => -1拉取全部文章,需要结合当前页码计算常规文章、插入文章的偏移量,避免分页内容错位。
内容的提问来源于stack exchange,提问作者Vander
相关产品推荐
相关产品推荐

