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

如何用get_terms筛选关联job-country为germany的job-category术语?

使用get_terms筛选关联特定分类术语的分类项

要实现仅显示关联了job-country分类中germany术语的job-category术语,我们可以通过先获取关联目标术语的文章ID,再反向筛选对应分类术语的方式,结合get_terms完成需求,具体实现如下:

// 1. 获取job-country分类下germany术语的ID
$germany_term = get_term_by('slug', 'germany', 'job-country');
if (!$germany_term || is_wp_error($germany_term)) {
    // 如果germany术语不存在,直接终止后续逻辑
    return;
}
$germany_term_id = $germany_term->term_id;

// 2. 获取所有关联了germany术语的job类型文章ID
$germany_posts = get_posts(array(
    'post_type' => 'job', // 替换为你的自定义文章类型slug
    'posts_per_page' => -1,
    'fields' => 'ids', // 仅返回文章ID,提升查询效率
    'tax_query' => array(
        array(
            'taxonomy' => 'job-country',
            'field' => 'term_id',
            'terms' => $germany_term_id,
        )
    )
));

// 3. 使用get_terms筛选关联上述文章的job-category术语
$job_categories = get_terms(array(
    'taxonomy' => 'job-category',
    'object_ids' => $germany_posts, // 仅保留关联指定文章的分类术语
    'hide_empty' => false, // 按需调整:true只显示有文章的分类,false显示所有关联过的
    'orderby' => 'name', // 按分类名称排序
    'order' => 'ASC'
));

// 循环输出筛选后的分类
if (!empty($job_categories) && !is_wp_error($job_categories)) {
    echo '<ul>';
    foreach ($job_categories as $category) {
        echo '<li><a href="' . get_term_link($category) . '">' . esc_html($category->name) . '</a></li>';
    }
    echo '</ul>';
}

关键说明:

  • object_ids参数:这是实现需求的核心,get_terms通过该参数仅返回关联指定文章ID的分类术语,间接实现跨分类的关联筛选。
  • 效率优化:获取文章时使用fields => 'ids'只返回ID列表,避免加载完整文章对象,减少资源消耗。
  • 容错处理:提前判断germany术语是否存在,避免后续查询出现无效参数;同时对get_terms的结果做错误校验。
  • 自定义适配:可根据站点实际情况修改post_type、hide_empty、orderby等参数,调整筛选和展示逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:52:08