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

WordPress:多文章类型共享分类时,如何单独获取单类型分类?

解决共享分类法下获取特定自定义文章类型已使用分类的问题

这个问题我之前也碰到过,确实WordPress的get_categories和get_terms本身没有直接指定文章类型的参数——毕竟共享分类法是绑定到文章对象而非文章类型的。不过有两个简洁有效的解决办法:

方法一:用wp_list_categories直接筛选(适合直接输出列表)

wp_list_categories其实支持post_type参数,能直接帮你过滤出指定文章类型下已使用的分类,代码非常简洁:

// 替换成你的目标分类法和文章类型
$args = array(
    'taxonomy' => 'your_shared_taxonomy', // 共享分类法的slug
    'post_type' => 'your_custom_post_type', // 目标自定义文章类型的slug
    'hide_empty' => true, // 只显示有文章关联的分类
    'title_li' => '', // 去掉默认的分类列表标题
    // 其他可选参数:orderby、order等
);

wp_list_categories($args);

方法二:用get_terms结合文章ID筛选(适合后续自定义处理)

如果需要先获取分类数据再做自定义逻辑(比如修改输出格式、统计数量等),可以先拿到目标文章类型的所有文章ID,再通过object_ids参数传给get_terms:

// 定义目标参数
$target_post_type = 'your_custom_post_type';
$target_taxonomy = 'your_shared_taxonomy';

// 1. 获取该文章类型下所有已发布文章的ID(只取ID提高效率)
$post_ids = get_posts(array(
    'post_type' => $target_post_type,
    'posts_per_page' => -1, // 取所有文章
    'fields' => 'ids',
    'post_status' => 'publish' // 可选,只包含已发布内容
));

// 2. 获取这些文章关联的分类
$used_terms = get_terms(array(
    'taxonomy' => $target_taxonomy,
    'object_ids' => $post_ids,
    'hide_empty' => true,
    'orderby' => 'name',
    'order' => 'ASC'
));

// 3. 自定义处理输出
if (!empty($used_terms) && !is_wp_error($used_terms)) {
    echo '<div class="custom-term-list">';
    foreach ($used_terms as $term) {
        echo '<a href="' . esc_url(get_term_link($term)) . '" class="term-item">' . esc_html($term->name) . '</a>';
    }
    echo '</div>';
}

注意事项

  • 如果你的自定义文章类型关联了多个共享分类法,只需要针对每个分类法单独调用上述方法即可;
  • hide_empty参数设为true时,会自动过滤掉没有关联任何文章的分类,结合文章类型筛选后,就能精准得到目标内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:11:55