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

WordPress如何获取指定文章自定义分类法术语并排除指定ID项

代码无法正常工作的原因

  • get_the_terms() 函数仅接收2个有效入参:文章ID、自定义分类法别名,你传入的第三个HTML参数不被函数识别,属于无效传参
  • 该函数执行成功后返回的是WP_Term对象组成的数组,PHP中直接输出数组默认会被转换为字符串array,无法输出具体的术语内容
  • 你提供的代码片段缺少语法闭合结构,本身存在语法错误

修复后的实现(支持排除指定ID术语)

// 获取当前文章关联的regisseur分类法术语
$regisseurs = get_the_terms( $post->ID, 'regisseur' );

// 校验返回结果合法,避免报错
if ( ! is_wp_error( $regisseurs ) && ! empty( $regisseurs ) ) {
    // 定义需要排除的术语ID
    $exclude_ids = [43, 76];
    $output = 'Regisseur: <span class="flight">';
    $term_list = [];

    foreach ( $regisseurs as $term ) {
        // 跳过需要排除的术语
        if ( in_array( $term->term_id, $exclude_ids ) ) {
            continue;
        }
        // 如果不需要跳转链接,直接写 $term_list[] = esc_html( $term->name ); 即可
        $term_list[] = '<a href="' . get_term_link( $term ) . '">' . esc_html( $term->name ) . '</a>';
    }

    // 拼接多术语分隔符、闭合标签后输出
    $output .= implode( ', ', $term_list );
    $output .= '</span>';
    echo $output;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:18:01