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

WordPress归档页如何仅展示分类搜索结果对应分类下的文章?

问题根源

  • 原代码未在查询参数中添加分类筛选规则,导致返回全量文章
  • 错误遍历所有分类执行查询,没有读取分类跳转时传递的目标分类参数
  • the_post($cat->cat_ID)写法无效,分类筛选需在查询参数中配置,无法通过该方法实现
  • 自定义查询未设置分页总数参数,会导致分页功能异常
  • 不必要的主查询替换逻辑会增加代码出错概率

修正后代码

直接替换你archive.php中原有的相关代码即可:

<div>
<?php
// 获取当前分类归档页对应的目标分类ID
$current_cat_id = get_queried_object_id();
// 读取当前分页参数
$paged = get_query_var('paged') ?: 1;

$args = [
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'paged'          => $paged,
    'posts_per_page' => 8,
    'cat'            => $current_cat_id // 分类筛选核心参数
];

$custom_query = new WP_Query($args);
if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : $custom_query->the_post(); ?>
        <div> Here is my post </div>
    <?php endwhile;
endif;
?>
</div>

<?php
the_posts_pagination([
    'mid_size' => 2,
    'total'    => $custom_query->max_num_pages // 适配自定义查询的分页总数
]);

// 重置查询,避免影响页面其他逻辑
wp_reset_postdata();
?>

生效说明

无需修改之前的分类下拉跳转逻辑,代码会自动识别跳转过来的分类,只输出对应分类下的文章,默认每页展示8篇,分页功能正常可用。

内容的提问来源于stack exchange,提问作者C.Sav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:57:04