You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress分类归档页优先显示Special分类文章问题求助

解决方案

要实现「优先显示当前归档分类下同时带有'Special'标签的文章,再显示该分类下剩余文章」的需求,核心是精准筛选分类交集并排除已展示的文章,具体代码如下:

<div class="projects-container">
    <?php
    // 获取当前归档分类的ID
    $current_cat_id = get_queried_object_id();
    // 获取'Special'分类的ID
    $special_cat_id = get_cat_ID('Special');
    
    // 1. 先查询同时属于当前分类和Special分类的文章
    $special_args = array(
        'category__and' => array($current_cat_id, $special_cat_id),
        'posts_per_page' => -1, // 显示所有符合条件的文章
    );
    $special_query = new WP_Query($special_args);
    
    // 存储已展示的文章ID,避免重复
    $displayed_post_ids = array();
    ?>

    <?php if ($special_query->have_posts()) : ?>
        <?php while ($special_query->have_posts()) : $special_query->the_post(); ?>
            <?php
            // 将当前文章ID加入已展示数组
            $displayed_post_ids[] = get_the_ID();
            ?>
            <!-- 这里放你的文章缩略图、标题代码,比如: -->
            <div class="project-item special">
                <?php the_post_thumbnail(); ?>
                <h3><?php the_title(); ?></h3>
            </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); // 重置查询 ?>
    <?php endif; ?>

    <?php
    // 2. 查询当前分类下未被展示的剩余文章(即不属于Special分类的)
    $remaining_args = array(
        'cat' => $current_cat_id, // 当前分类ID
        'post__not_in' => $displayed_post_ids, // 排除已展示的文章
        'posts_per_page' => -1,
    );
    $remaining_query = new WP_Query($remaining_args);
    ?>

    <?php if ($remaining_query->have_posts()) : ?>
        <?php while ($remaining_query->have_posts()) : $remaining_query->the_post(); ?>
            <!-- 这里放你的文章缩略图、标题代码,比如: -->
            <div class="project-item">
                <?php the_post_thumbnail(); ?>
                <h3><?php the_title(); ?></h3>
            </div>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); // 重置查询 ?>
    <?php endif; ?>
</div>

关键说明

  • get_queried_object_id():分类归档页中,该函数能直接获取当前分类的ID,无需手动指定。
  • category__and:用于筛选同时属于多个分类的文章,确保只显示当前分类+Special分类的交集内容。
  • post__not_in:通过存储已展示的文章ID,在第二个查询中排除这些内容,彻底避免重复显示。
  • posts_per_page => -1:表示显示所有符合条件的文章,若你需要分页,可修改为具体数字(如10)。

内容的提问来源于stack exchange,提问作者André do Carmo Gonçalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:12:49