如何从给定WP_Query中获取匹配指定ID的taxonomy分类标题
实现方法
你可以直接使用WordPress原生的get_term()函数获取术语对象,取对象的name属性即可得到分类标题,示例代码如下:
// 获取taxonomy为interests、ID为23的分类标题 $interest_term = get_term( 23, 'interests' ); if ( ! is_wp_error( $interest_term ) ) { $interest_title = $interest_term->name; // 直接输出即可使用 echo $interest_title; } // 获取taxonomy为co-curriculum、ID为45的分类标题 $curriculum_term = get_term( 45, 'co-curriculum' ); if ( ! is_wp_error( $curriculum_term ) ) { $curriculum_title = $curriculum_term->name; }
如果需要批量处理多组分类法和ID的对应关系,可以用数组遍历简化代码:
// 定义分类法和对应ID的映射 $term_config = [ 'interests' => 23, 'co-curriculum' => 45 ]; $term_titles = []; foreach ( $term_config as $taxonomy => $term_id ) { $term = get_term( $term_id, $taxonomy ); if ( ! is_wp_error( $term ) ) { $term_titles[ $taxonomy ] = $term->name; } } // 输出所有标题示例:print_r($term_titles);
补充注意点
- 你现有代码中的WP_Query使用了
relation => 'AND',意味着查询的enrolments文章需要同时属于interests分类下的23/45、以及co-curriculum分类下的23/45,若你只需要匹配任意一个分类的对应ID,可将relation改为OR。 - 如果你需要从查询到的文章中获取关联的所有对应分类标题,可在WP_Query的循环中使用
wp_get_post_terms( get_the_ID(), '分类法名称' )批量获取文章关联的术语列表。
内容的提问来源于stack exchange,提问作者monsaic123
相关产品推荐
相关产品推荐

