get_the_terms( int|WP_Post $post, string $taxonomy )
Retrieve the terms of the taxonomy that are attached to the post.
Description Description
Parameters Parameters
- $post
-
(int|WP_Post) (Required) Post ID or object.
- $taxonomy
-
(string) (Required) Taxonomy name.
Return Return
(WP_Term[]|false|WP_Error) Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.
Source Source
File: wp-includes/category-template.php
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; }
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
2.5.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
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] =>
)
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:Expand full source codeCollapse full source code
Get terms for all custom taxonomies
Place this function in your theme’s
functions.php
.Expand full source codeCollapse full source code
Now you can use this function in your theme:
Optimized way to get a comma separated list of terms.
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).The function returns WP_Error if the $taxonomy doesn’t exist.
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.
Expand full source codeCollapse full source code
Another example how to get custom post type taxonomies and separate them with commas.