get_the_terms()
云策文档标注
概述
get_the_terms() 函数用于检索与指定文章关联的特定分类法术语。它返回一个 WP_Term 对象数组,支持缓存机制以提高性能,并包含错误处理。
关键要点
- 参数:$post(必需,文章 ID 或 WP_Post 对象)和 $taxonomy(必需,分类法名称)。
- 返回值:成功时返回 WP_Term 对象数组;若无术语或文章不存在则返回 false;失败时返回 WP_Error。
- 缓存:函数利用 get_object_term_cache() 和 wp_cache_add() 缓存术语数据,减少数据库查询。
- 过滤器:通过 apply_filters('get_the_terms', ...) 允许自定义术语列表。
- 相关函数:与 wp_get_object_terms() 类似,但 get_the_terms() 具有缓存优势。
代码示例
// 基本用法:获取文章的分类术语
$terms = get_the_terms( get_the_ID(), 'category' );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo $term->name;
}
}
// 获取逗号分隔的术语列表
$term_obj_list = get_the_terms( $post->ID, 'taxonomy' );
$terms_string = join(', ', wp_list_pluck($term_obj_list, 'name'));注意事项
- 确保 $taxonomy 参数存在,否则函数可能返回 WP_Error。
- 在循环中调用时,缓存机制可提升性能,但需注意数据一致性。
- 返回的术语数组可能为空,应使用 is_wp_error() 和 empty() 进行错误检查。
原文内容
Retrieves the terms of the taxonomy that are attached to the post.
Parameters
$postint|WP_Postrequired-
Post ID or object.
$taxonomystringrequired-
Taxonomy name.
Source
function get_the_terms( $post, $taxonomy ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$terms = get_object_term_cache( $post->ID, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post->ID, $taxonomy );
if ( ! is_wp_error( $terms ) ) {
$term_ids = wp_list_pluck( $terms, 'term_id' );
wp_cache_add( $post->ID, $term_ids, $taxonomy . '_relationships' );
}
}
/**
* Filters the list of terms attached to the given post.
*
* @since 3.1.0
*
* @param WP_Term[]|WP_Error $terms Array of attached terms, or WP_Error on failure.
* @param int $post_id Post ID.
* @param string $taxonomy Name of the taxonomy.
*/
$terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );
if ( empty( $terms ) ) {
return false;
}
return $terms;
}
Hooks
- apply_filters( ‘get_the_terms’, WP_Term[]|WP_Error $terms, int $post_id, string $taxonomy )
-
Filters the list of terms attached to the given post.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 12 content
mklusak
WP_Term object properties: (because I am always looking for them)
WP_Term Object ( [term_id] => [name] => [slug] => [term_group] => [term_taxonomy_id] => [taxonomy] => [description] => [parent] => [count] => [filter] => )Skip to note 13 content
benklocek
Optimized way to get a comma separated list of terms.
$term_obj_list = get_the_terms( $post->ID, 'taxonomy' ); $terms_string = join(', ', wp_list_pluck($term_obj_list, 'name'));Skip to note 14 content
Dustin Falgout
The difference between this function and
wp_get_post_terms()is that this function’s results are cached (thus, it won’t hit the database every time its called).Skip to note 15 content
Codex
Get terms for all custom taxonomies
Place this function in your theme’s
functions.php./** * Get taxonomies terms links. * * @see get_object_taxonomies() */ function wpdocs_custom_taxonomies_terms_links() { // Get post by post ID. if ( ! $post = get_post() ) { return ''; } // Get post type by post. $post_type = $post->post_type; // Get post type taxonomies. $taxonomies = get_object_taxonomies( $post_type, 'objects' ); $out = array(); foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){ // Get the terms related to post. $terms = get_the_terms( $post->ID, $taxonomy_slug ); if ( ! empty( $terms ) ) { $out[] = "<h2>" . $taxonomy->label . "</h2>n<ul>"; foreach ( $terms as $term ) { $out[] = sprintf( '<li><a href="%1$s">%2$s</a></li>', esc_url( get_term_link( $term->slug, $taxonomy_slug ) ), esc_html( $term->name ) ); } $out[] = "n</ul>n"; } } return implode( '', $out ); } ?>Now you can use this function in your theme:
Skip to note 16 content
Codex
A Basic Example
Echoing the list of terms (for a taxonomy called
on-draught). This is similar to the output fromget_the_term_list, but without the terms being hyperlinked:$terms = get_the_terms( get_the_ID(), 'on-draught' ); if ( $terms && ! is_wp_error( $terms ) ) : $draught_links = array(); foreach ( $terms as $term ) { $draught_links[] = $term->name; } $on_draught = join( ", ", $draught_links ); ?> <p class="beers draught"> %s</span>', 'textdomain' ), esc_html( $on_draught ) ); ?> </p>Skip to note 17 content
Brian Layman
Another example of how to process the results of this call.
This example retrieves the categories and tags for a post and uses wp_list_pluck() to efficiently creates a list of their names, without duplicates, and turns it into a string of keys suitable for an NITF feed.
// Get a list of categories and extract their names $post_categories = get_the_terms( $post->ID, 'category' ); if ( ! empty( $post_categories ) && ! is_wp_error( $post_categories ) ) { $categories = wp_list_pluck( $post_categories, 'name' ); } // Get a list of tags and extract their names $post_tags = get_the_terms( $post->ID, 'post_tag' ); if ( ! empty( $post_tags ) && ! is_wp_error( $post_tags ) ) { $tags = wp_list_pluck( $post_tags, 'name' ); } // Combine Categories and tags, with category first $tagCats = array_merge( $categories, $tags ); // Process to desired format $keyList = '<key-list>' . PHP_EOL . ' <keyword key="' . implode( $tagCats, '"/>' . PHP_EOL . ' <keyword key="') . '"/>' . PHP_EOL . '</key-list>' . PHP_EOL;Skip to note 18 content
Everaldo Matias
Example of a wrap function for get_the_terms() with a return list of terms added to the post.
Exemplo de função wrap para get_the_terms() , que retorna a lista de termos adicionadas ao post.
if ( ! function_exists( 'wpdocs_example_get_the_terms' ) ) { /** * Function to return list of the terms. * * @param string 'taxonomy' * * @return html Returns the list of elements. */ function wpdocs_example_get_the_terms( $taxonomy ) { $terms = get_the_terms( get_the_ID(), $taxonomy ); if ( $terms && ! is_wp_error( $terms ) ) : $term_links = array(); foreach ( $terms as $term ) { $term_links[] = '<a href="' . esc_attr( get_term_link( $term->slug, $taxonomy ) ) . '">' . __( $term->name ) . '</a>'; } $all_terms = join( ', ', $term_links ); echo '<span class="terms-' . esc_attr( $term->slug ) . '">' . __( $all_terms ) . '</span>'; endif; } }How to use:
Como usar:
wpdocs_example_get_the_terms( 'taxonomy' )Skip to note 19 content
Pedro Carvalho
The function returns WP_Error if the $taxonomy doesn’t exist.
Skip to note 20 content
soullighter
Another example how to get custom post type taxonomies and separate them with commas.
$terms = get_the_terms( $post->ID , array( 'teams_positions') ); // init counter $i = 1; foreach ( $terms as $term ) { $term_link = get_term_link( $term, array( 'teams_positions') ); if( is_wp_error( $term_link ) ) continue; echo $term->name; // Add comma (except after the last theme) echo ($i < count($terms))? " / " : ""; // Increment counter $i++; }Skip to note 21 content
tomaaszq
if you want to use this inside WP Query, just to list your taxonomy names, then you can use:
<ul> foreach ( get_the_terms( get_the_ID(), 'taxonomy_name' ) as $tax ) { echo '<li>' . __( $tax->name ) . '</li>'; } </ul>Skip to note 22 content
Narendra Sishodiya
A basic example of getting parent categories only.
$section_slug_array = get_the_terms( get_the_ID(),'section' ); $parent_menu_list = array(); if ( ! is_wp_error( $section_slug_array ) && is_array( $section_slug_array ) ) { foreach ( $section_slug_array as $term ) { if ( 0 === $term->parent ) { $parent_menu_list[] = $term->slug; } } } print_r( $parent_menu_list );