get_the_terms()
Gets the taxonomy elements (terms) that are attached to the specified post.
This function can be used inside The Loop. Or you can pass it the ID of the post the terms of whose you want to get.
This function is completely identical to wp_get_object_terms( $id, $taxonomy ). The difference is that this function works with the cache and there is a filter get_the_terms
.
The function will retrieve only those terms (taxonomy items) that are checked on the post edit page.

I.e. in this case the function will only get the marked terms.
Hooks from the function
Return
WP_Term[]|false|WP_Error
.
Array
― of WP_Term objects on success.false
― if there are no terms or the specified post does not exist.WP_Error
― in other cases.
Usage
get_the_terms( $post, $taxonomy );
- $post(int|WP_Post) (required)
- Post ID or object.
- $taxonomy(string) (required)
- Taxonomy name.
Examples
#1 Get only the first term
Let's say we get the post terms and we need to get the data of only one term (taxonomy element). But this function returns an array of term objects. The example below shows how to get the first term from the array.
$terms = get_the_terms( $post, 'my_tax' ); if( $terms ){ $term = array_shift( $terms ); // get first // now you can display the name of the term echo $term->name; }
#2 Display links of the 'my_tax' taxonomy elements attached to the post 10
$cur_terms = get_the_terms( 10, 'my_tax' ); if( is_array( $cur_terms ) ){ foreach( $cur_terms as $cur_term ){ echo '<a href="'. get_term_link( $cur_term->term_id, $cur_term->taxonomy ) .'">'. $cur_term->name .'</a>,'; } }
The same can be done inside The Loop:
Display the attached terms for each post. To do this, specify the post ID dynamically ($post->ID):
$cur_terms = get_the_terms( $post, 'my_tax' ); if( is_array( $cur_terms ) ){ foreach( $cur_terms as $cur_term ){ echo '<a href="'. get_term_link( $cur_term->term_id, $cur_term->taxonomy ) .'">'. $cur_term->name .'</a>,'; } }
#3 Get the top-level term for the specified or current post in The Loop
Here we have a custom function based on get_the_terms():
/** * Gets the top-level term for the specified or current post in The Loop. * * @param string $taxonomy * @param int/object $post_id ID or object of the post * * @return string/wp_error Объект термина или false */ function get_top_term( $taxonomy, $post_id = 0 ){ if( isset($post_id->ID) ) $post_id = $post_id->ID; if( ! $post_id ) $post_id = get_the_ID(); $terms = get_the_terms( $post_id, $taxonomy ); if( ! $terms || is_wp_error($terms) ) return $terms; // only first $term = array_shift( $terms ); // find TOP $parent_id = $term->parent; while( $parent_id ){ $term = get_term_by( 'id', $parent_id, $term->taxonomy ); $parent_id = $term->parent; } return $term; }
Usage:
$top_term = get_top_term( 'category' ); echo $top_term->name;
Changelog
Since 2.5.0 | Introduced. |