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

如何从WordPress的WP_Term数组中提取term_id存入变量

实现方案

你可以用WordPress内置的wp_list_pluck函数快速提取所有term_id,同时注意提前判断get_the_terms的返回结果避免报错,完整代码如下:

$themes = get_the_terms( get_post(), TAXONOMY_THEME );
$themes_id = [];

// 排除查询错误、无对应分类术语的情况
if ( $themes && ! is_wp_error( $themes ) ) {
    $themes_id = wp_list_pluck( $themes, 'term_id' );
}

说明

  • wp_list_pluck是WordPress官方封装的工具函数,支持从对象数组/关联数组中批量提取指定字段的值,自动生成新数组,不需要手动遍历
  • 最终得到的$themes_id就是格式为[22,27]的分类ID数组,可直接用于后续WP_Query的tax_query参数做关联文章筛选

如果你不习惯用内置函数,也可以手动遍历实现:

$themes = get_the_terms( get_post(), TAXONOMY_THEME );
$themes_id = [];
if ( $themes && ! is_wp_error( $themes ) ) {
    foreach ( $themes as $term ) {
        $themes_id[] = $term->term_id;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:45:01