The get_the_terms() WordPress PHP function retrieves the terms of a taxonomy that are attached to a post.
Usage
get_the_terms($post, $taxonomy);
Example:
$categories = get_the_terms($post->ID, 'category');
Parameters
$post
(int|WP_Post) – Required. Post ID or object.$taxonomy
(string) – Required. Taxonomy name.
More information
See WordPress Developer Resources: get_the_terms()
Examples
Displaying categories of a post
This example retrieves the categories of a post and displays them as a list.
$categories = get_the_terms($post->ID, 'category'); if ($categories && !is_wp_error($categories)) { echo '<ul>'; foreach ($categories as $category) { echo '<li>' . $category->name . '</li>'; } echo '</ul>'; }
Displaying custom taxonomy terms of a post
This example retrieves the terms of a custom taxonomy called genre
and displays them as a comma-separated list.
$genres = get_the_terms($post->ID, 'genre'); if ($genres && !is_wp_error($genres)) { $genre_names = wp_list_pluck($genres, 'name'); echo implode(', ', $genre_names); }
Displaying terms of all taxonomies attached to a post
This example retrieves the terms of all taxonomies attached to a post and displays them in separate lists.
$taxonomies = get_object_taxonomies($post->post_type, 'objects'); foreach ($taxonomies as $taxonomy_slug => $taxonomy) { $terms = get_the_terms($post->ID, $taxonomy_slug); if ($terms && !is_wp_error($terms)) { echo '<h2>' . $taxonomy->label . '</h2><ul>'; foreach ($terms as $term) { echo '<li>' . $term->name . '</li>'; } echo '</ul>'; } }
Displaying term names with their links
This example retrieves the categories of a post and displays them as a list with links to their respective archive pages.
$categories = get_the_terms($post->ID, 'category'); if ($categories && !is_wp_error($categories)) { echo '<ul>'; foreach ($categories as $category) { echo '<li><a href="' . get_term_link($category) . '">' . $category->name . '</a></li>'; } echo '</ul>'; }
Displaying term names with custom HTML
This example retrieves the tags of a post and displays them with custom HTML.
$tags = get_the_terms($post->ID, 'post_tag'); if ($tags && !is_wp_error($tags)) { echo '<div class="tags">'; foreach ($tags as $tag) { echo '<span class="tag">' . $tag->name . '</span>'; } echo '</div>'; }