The get_the_terms() WordPress PHP function retrieves the terms of a specified taxonomy that are attached to a specific post.
Usage
$terms = get_the_terms($post, $taxonomy); // your custom code here return $terms;
Parameters
$post
(int|WP_Post) – Required. The post ID or object.$taxonomy
(string) – Required. The taxonomy name.
More information
See WordPress Developer Resources: get_the_terms()
Examples
Get categories of a post
Retrieve the categories associated with a post and display them in a list.
$categories = get_the_terms(get_the_ID(), 'category'); if ($categories) { echo '<ul>'; foreach ($categories as $category) { echo '<li>' . $category->name . '</li>'; } echo '</ul>'; }
Get tags of a post
Retrieve the tags associated with a post and display them in a list.
$tags = get_the_terms(get_the_ID(), 'post_tag'); if ($tags) { echo '<ul>'; foreach ($tags as $tag) { echo '<li>' . $tag->name . '</li>'; } echo '</ul>'; }
Display custom taxonomy terms for a custom post type
Get the terms of a custom taxonomy called ‘genre’ for a custom post type called ‘book’.
$genres = get_the_terms(get_the_ID(), 'genre'); if ($genres) { echo '<ul>'; foreach ($genres as $genre) { echo '<li>' . $genre->name . '</li>'; } echo '</ul>'; }
Get term link for each term
Retrieve the terms of a taxonomy and display them as links.
$categories = get_the_terms(get_the_ID(), 'category'); if ($categories) { echo '<ul>'; foreach ($categories as $category) { $term_link = get_term_link($category); echo '<li><a href="' . $term_link . '">' . $category->name . '</a></li>'; } echo '</ul>'; }
Check if a post has a specific term
Check if a post has a specific category (e.g., ‘Featured’).
$categories = get_the_terms(get_the_ID(), 'category'); $has_featured = false; if ($categories) { foreach ($categories as $category) { if ($category->name == 'Featured') { $has_featured = true; break; } } } if ($has_featured) { echo 'This post is featured!'; } else { echo 'This post is not featured.'; }