使用分类筛选时WordPress置顶帖子无法优先显示问题求助
解决WordPress分类筛选时置顶文章不生效的问题
嘿,我瞅出你代码里的问题啦!咱们来一步步搞定这个置顶文章在分类筛选时失效的问题:
问题根源分析
你当前的代码用了post__in => $sticky参数,这会强制查询只返回这些置顶文章,但有两个坑:
- 如果某篇置顶文章不属于你指定的
$cattoShow分类,它会直接被过滤掉,不会出现在结果里; - 就算有符合分类的置顶文章,你的
orderby设为date,没给置顶文章优先排序的权重,所以它们不会自动排到最前面。
而当你不指定cat参数时,post__in能拿到所有置顶文章,所以看起来正常,但加了分类筛选后,这两个问题就暴露出来了。
解决方案一:分开查询置顶与普通文章(更可靠)
这个方法是先单独拉取当前分类下的置顶文章,再拉取该分类下的非置顶文章,最后合并结果,确保置顶文章优先显示:
// 获取系统存储的置顶文章ID数组 $sticky = get_option('sticky_posts'); // 处理空数组的情况,避免WP_Query报错 if (empty($sticky)) $sticky = array(0); // 第一步:查询当前分类下的置顶文章 $sticky_args = array( 'posts_per_page' => intval($blogtoShow), 'post_status' => 'publish', 'post_type' => 'post', 'cat' => $cattoShow, 'post__in' => $sticky, 'ignore_sticky_posts' => true, // 关闭WP自动置顶排序,避免干扰 'orderby' => 'date', 'order' => 'DESC' ); $sticky_query = new WP_Query($sticky_args); // 第二步:查询当前分类下的非置顶文章,排除已经显示的置顶文章 $normal_args = array( 'posts_per_page' => intval($blogtoShow) - $sticky_query->found_posts, 'post_status' => 'publish', 'post_type' => 'post', 'cat' => $cattoShow, 'post__not_in' => $sticky, 'orderby' => 'date', 'order' => 'DESC' ); $normal_query = new WP_Query($normal_args); // 合并两个查询的结果 $the_query = new WP_Query(); $the_query->posts = array_merge($sticky_query->posts, $normal_query->posts); $the_query->post_count = count($the_query->posts); $the_query->found_posts = $sticky_query->found_posts + $normal_query->found_posts; // 正常循环输出文章 if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); // 这里写你的文章内容输出逻辑,比如标题、摘要等 the_title('<h2>', '</h2>'); the_excerpt(); endwhile; wp_reset_postdata(); // 重置查询,避免影响后续内容 endif;
解决方案二:利用WordPress原生的置顶排序参数
WordPress的orderby参数支持sticky_posts值,可以直接让置顶文章优先显示,再按日期排序普通文章,代码更简洁:
$sticky = get_option('sticky_posts'); $args = array( 'posts_per_page' => intval($blogtoShow), 'post_status' => 'publish', 'post_type' => 'post', 'cat' => $cattoShow, 'orderby' => 'sticky_posts date', // 先按置顶权重排序,再按日期排序 'order' => 'DESC', 'ignore_sticky_posts' => false // 保持默认,让WP处理置顶逻辑 ); $the_query = new WP_Query($args); if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); // 你的文章内容输出逻辑 the_title('<h2>', '</h2>'); the_content(); endwhile; wp_reset_postdata(); endif;
注意点
第二种方案依赖WordPress原生的置顶排序逻辑,大多数情况下都能正常工作,但如果你的主题或插件修改了默认的WP_Query行为,可能需要测试验证一下效果。
内容的提问来源于stack exchange,提问作者Owais Bin Rizwan
相关产品推荐
相关产品推荐

