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

如何获取特定分类及其子分类下已发布文章的年份列表?

两种实现方式:包含子分类的年份列表获取

方法一:修改现有SQL查询

你原来的SQL只匹配了单个分类的slug,要包含子分类,得先拿到目标分类及其所有子分类的ID集合,再用IN条件匹配。同时建议加上自定义分类法的过滤,避免不同分类法出现slug冲突的问题。

代码示例:

// 替换为你的实际参数
$custom_taxonomy = 'your_taxonomy_name';
$custom_post_type = 'your_post_type_name';
$target_cat_slug = 'target_category_slug';

// 获取目标分类的term对象
$target_term = get_term_by('slug', $target_cat_slug, $custom_taxonomy);
if (!$target_term || is_wp_error($target_term)) {
    $years = [];
    return;
}

// 获取所有子分类ID,同时加入父分类ID
$term_ids = get_term_children($target_term->term_id, $custom_taxonomy);
$term_ids[] = $target_term->term_id;

// 准备带IN条件的SQL查询
$placeholders = implode(',', array_fill(0, count($term_ids), '%d'));
$query_prepare = $wpdb->prepare("
    SELECT YEAR(post_date) AS post_year
    FROM $wpdb->posts AS p 
    INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id)
    INNER JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
    WHERE post_status = 'publish' 
      AND post_type = %s 
      AND tt.taxonomy = %s 
      AND tt.term_id IN ($placeholders)
    GROUP BY post_year
    ORDER BY post_year DESC", 
    array_merge([$custom_post_type, $custom_taxonomy], $term_ids)
);

// 直接获取年份数组,无需处理对象
$years = $wpdb->get_col($query_prepare);

方法二:使用WP_Query实现

如果不想直接操作数据库,用WP_Query的tax_query参数,设置include_children为true即可自动包含子分类内容,之后提取年份并去重排序。

代码示例:

// 替换为你的实际参数
$custom_taxonomy = 'your_taxonomy_name';
$custom_post_type = 'your_post_type_name';
$target_cat_slug = 'target_category_slug';

// 构建查询参数
$args = [
    'post_type' => $custom_post_type,
    'post_status' => 'publish',
    'posts_per_page' => -1, // 获取所有符合条件的文章
    'tax_query' => [
        [
            'taxonomy' => $custom_taxonomy,
            'field' => 'slug',
            'terms' => $target_cat_slug,
            'include_children' => true, // 开启子分类包含
        ],
    ],
    'fields' => 'ids', // 只获取文章ID,减少数据加载
];

$query = new WP_Query($args);

$years = [];
if ($query->have_posts()) {
    // 遍历提取年份并去重
    foreach ($query->posts as $post_id) {
        $year = get_the_date('Y', $post_id);
        if (!in_array($year, $years)) {
            $years[] = $year;
        }
    }
    // 按年份倒序排列
    rsort($years);
}

wp_reset_postdata(); // 重置查询状态

注意事项

  • 两种方法都需要替换代码中的占位参数为你实际的自定义分类法、文章类型和目标分类slug
  • SQL方法性能更优,适合内容量较大的场景,直接从数据库聚合年份
  • WP_Query方法更贴合WordPress编码规范,无需直接操作数据库,逻辑更直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 15:17:57