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

WordPress获取当前分类ID异常:全部分类文章被显示

问题解决方法

你的代码问题出在get_posts的参数使用错误:category参数对应的是分类的别名(slug),而非分类ID,传入ID后无法匹配目标分类,所以返回了全部分类的文章。

下面是修正后的两种可行方案:

方案1:修正参数为cat(直接传入分类ID)

<select id="post-select">
  <?php
    $current_cat_id = get_query_var('cat');
    $posts = get_posts(array(
      'cat' => $current_cat_id,
      'numberposts' => -1
    ));
    foreach ($posts as $post) {
      setup_postdata($post); // 初始化post数据,确保相关函数正常工作
      echo '<option value="' . get_permalink($post->ID) . '">' . $post->post_title . '</option>';
    }
    wp_reset_postdata(); // 重置post数据,避免影响后续查询
  ?>
</select>

<script>
  document.getElementById("post-select").addEventListener("change", function() {
    window.location = this.value;
  });
</script>

方案2:用get_queried_object_id()更可靠获取分类ID

在分类归档页面,get_queried_object_id()能直接获取当前分类的ID,比get_query_var('cat')兼容性更好:

<select id="post-select">
  <?php
    $current_cat_id = get_queried_object_id();
    $posts = get_posts(array(
      'category__in' => array($current_cat_id), // 用数组形式传入分类ID
      'numberposts' => -1
    ));
    foreach ($posts as $post) {
      setup_postdata($post);
      echo '<option value="' . get_permalink($post->ID) . '">' . $post->post_title . '</option>';
    }
    wp_reset_postdata();
  ?>
</select>

<script>
  document.getElementById("post-select").addEventListener("change", function() {
    window.location = this.value;
  });
</script>

补充说明:循环自定义获取的文章时,必须加上setup_postdata($post)和wp_reset_postdata(),避免主查询的post数据被污染,确保get_permalink等函数正常运行。

内容的提问来源于stack exchange,提问作者Mahsuns Seven

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:31:49