如何从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
相关产品推荐
相关产品推荐

