How to Display Taxonomies in WordPress Using get_the_terms(): A Comprehensive Guide

How to Display Taxonomies in WordPress Using get_the_terms(): A Comprehensive Guide

How to Display Taxonomies in WordPress Using get_the_terms() A Comprehensive Guide

Feb 17th, 2025

By, Editorial Team

WordPress

Taxonomies are one of the most powerful features in WordPress. They allow you to organize your content into categories, tags, or custom classifications, making it easier for users to navigate your site. Whether you’re running a blog, an e-commerce store, or a portfolio website, taxonomies play a critical role in enhancing user experience and improving SEO.

In this guide, we’ll explore how to use the get_the_terms() function in WordPress to display taxonomies effectively. By the end of this article, you’ll have a clear understanding of how to implement this function in your themes or plugins, along with practical examples and best practices.

1. What Are Taxonomies in WordPress?

Before diving into get_the_terms(), let’s take a moment to understand what taxonomies are and why they’re so important in WordPress.

In simple terms, taxonomies are a way to group and organize your content. Think of them as labels or categories that help you classify posts, pages, or custom post types based on shared characteristics. They play a crucial role in improving both user experience and SEO by making your site easier to navigate and understand.

Here’s a breakdown of the main types of taxonomies in WordPress:

1. Categories

Categories are hierarchical taxonomies , meaning they can have parent-child relationships. For example, you might have a “Recipes” category with subcategories like “Breakfast,” “Lunch,” and “Dinner.” Categories are ideal for grouping content into broader sections, providing a clear structure to your site.

2. Tags

Tags are non-hierarchical taxonomies that allow for more granular organization. Unlike categories, tags don’t have a structured hierarchy. For instance, a blog post about “WordPress SEO Tips” might include tags like “SEO,” “Plugins,” and “Performance.” Tags are great for highlighting specific topics or keywords within your content.

3. Custom Taxonomies

Custom taxonomies are user-defined classifications that you can create to suit your site’s unique needs. For example, if you run a movie review site, you might create a custom taxonomy called “Genres” with terms like “Action,” “Comedy,” and “Drama.” Custom taxonomies give you the flexibility to organize content in ways that make sense for your niche.

1.1 Why Do Taxonomies Matter?

Taxonomies are more than just organizational tools—they’re essential for creating a seamless user experience and boosting your site’s SEO. By categorizing your content effectively:

  • Visitors can easily find related posts, improving engagement.
  • Search engines gain a clearer understanding of your site’s structure, which can lead to better rankings.
  • Your site becomes more intuitive and professional, enhancing its overall appeal.

In short, taxonomies are the backbone of content organization in WordPress. Mastering how to display and utilize them—using functions like get_the_terms()—can take your site to the next level.

2. Why Use get_the_terms()?

The get_the_terms() function is a built-in WordPress function that retrieves the terms associated with a specific post or custom post type. It’s particularly useful because:

  • Flexibility: You can fetch terms from any taxonomy (categories, tags, or custom taxonomies).
  • Performance: It’s optimized for retrieving term data efficiently.
  • Customization: You can format and display terms in creative ways to enhance your site’s design.

Compared to similar functions like wp_get_post_terms() or get_the_term_list(), get_the_terms() offers a balance of simplicity and power, making it ideal for most use cases.

3. Basic Syntax of get_the_terms()

Here’s the basic syntax of the get_the_terms() function:

<?php

$terms = get_the_terms( $post_id, $taxonomy );

?>

3.1 Parameters:

  1. $post_id (int): The ID of the post you want to retrieve terms for. Use get_the_ID() if you’re working within the loop.
  2. $taxonomy (string): The name of the taxonomy (e.g., ‘category’, ‘post_tag‘, or a custom taxonomy like ‘genre’).

3.2 Return Value:

  • If successful, the function returns an array of term objects.
  • If no terms are found, it returns false.
  • If there’s an error, it returns a WP_Error object.

4. Step-by-Step Guide to Displaying Taxonomies

Now, let’s walk through how to use get_the_terms() to display taxonomies on your WordPress site.

4.1 Step 1: Retrieve Terms Within the Loop

If you’re working inside the WordPress loop, you can use get_the_ID() to automatically fetch the current post’s ID. Here’s an example:

<?php

if ( have_posts() ) :

    while ( have_posts() ) : the_post();

        $terms = get_the_terms( get_the_ID(), ‘category’ );

        if ( $terms && ! is_wp_error( $terms ) ) {

            echo ‘<ul>’;

            foreach ( $terms as $term ) {

                echo ‘<li><a href=”‘ . esc_url( get_term_link( $term ) ) . ‘”>’ . esc_html( $term->name ) . ‘</a></li>’;

            }

            echo ‘</ul>’;

        } else {

            echo ‘<p>No categories found.</p>’;

        }

    endwhile;

endif;

?>

Explanation:

  1. We retrieve the terms for the ‘category’ taxonomy.
  2. We check if terms exist and ensure there’s no error.
  3. We loop through the terms and display them as clickable links using get_term_link().

4.2 Step 2: Display Tags Outside the Loop

You can also use get_the_terms() outside the loop by specifying a post ID manually. For example:

<?php

$post_id = 42; // Replace with your desired post ID

$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”><a href=”‘ . esc_url( get_term_link( $tag ) ) . ‘”>’ . esc_html( $tag->name ) . ‘</a></span>’;

    }

    echo ‘</div>’;

} else {

    echo ‘<p>No tags found.</p>’;

}

?>

This approach is useful for displaying tags in sidebars, footers, or other non-loop areas.

4.3 Step 3: Display Custom Taxonomy Terms

For custom taxonomies, simply replace the taxonomy name. For instance, if you have a custom taxonomy called ‘genre’:

<?php

$genres = get_the_terms( get_the_ID(), ‘genre’ );

if ( $genres && ! is_wp_error( $genres ) ) {

    echo ‘<ul class=”genres”>’;

    foreach ( $genres as $genre ) {

        echo ‘<li><a href=”‘ . esc_url( get_term_link( $genre ) ) . ‘”>’ . esc_html( $genre->name ) . ‘</a></li>’;

    }

    echo ‘</ul>’;

} else {

    echo ‘<p>No genres found.</p>’;

}

?>

5. Advanced Techniques for Enhanced Displays

Unlock the full potential of your WordPress site with advanced taxonomy displays. By mastering techniques like adding icons or images to terms, dynamically filtering and sorting terms, and optimizing performance with caching, you can create visually stunning and highly functional designs. These methods not only enhance user experience but also improve site efficiency.

5.1 Add Icons or Images to Terms

You can associate icons or images with terms using Advanced Custom Fields (ACF) or custom fields. For example:

<?php

$terms = get_the_terms( get_the_ID(), ‘category’ );

if ( $terms && ! is_wp_error( $terms ) ) {

    echo ‘<div class=”categories-with-icons”>’;

    foreach ( $terms as $term ) {

        $icon_url = get_field( ‘category_icon’, $term ); // Assuming ACF field exists

        echo ‘<div class=”category-item”>’;

        if ( $icon_url ) {

            echo ‘<img src=”‘ . esc_url( $icon_url ) . ‘” alt=”‘ . esc_attr( $term->name ) . ‘”>’;

        }

        echo ‘<a href=”‘ . esc_url( get_term_link( $term ) ) . ‘”>’ . esc_html( $term->name ) . ‘</a>’;

        echo ‘</div>’;

    }

    echo ‘</div>’;

}

?>

5.2 Filter and Sort Terms Dynamically

You can filter terms based on criteria like count or name. For example, to display only the top 3 categories:

<?php

$terms = get_the_terms( get_the_ID(), ‘category’ );

if ( $terms && ! is_wp_error( $terms ) ) {

    usort( $terms, function( $a, $b ) {

        return $b->count – $a->count; // Sort by term count (descending)

    });

    $top_terms = array_slice( $terms, 0, 3 ); // Get top 3 terms

    echo ‘<ul>’;

    foreach ( $top_terms as $term ) {

        echo ‘<li><a href=”‘ . esc_url( get_term_link( $term ) ) . ‘”>’ . esc_html( $term->name ) . ‘</a></li>’;

    }

    echo ‘</ul>’;

}

?>

5.3 Optimize Performance with Caching

To improve performance, especially on high-traffic sites, consider caching the results of get_the_terms() using WordPress transients:

<?php

$post_id = get_the_ID();

$cache_key = ‘post_terms_’ . $post_id;

$terms = get_transient( $cache_key );

if ( false === $terms ) {

    $terms = get_the_terms( $post_id, ‘category’ );

    set_transient( $cache_key, $terms, DAY_IN_SECONDS ); // Cache for 24 hours

}

if ( $terms && ! is_wp_error( $terms ) ) {

    echo ‘<ul>’;

    foreach ( $terms as $term ) {

        echo ‘<li><a href=”‘ . esc_url( get_term_link( $term ) ) . ‘”>’ . esc_html( $term->name ) . ‘</a></li>’;

    }

    echo ‘</ul>’;

}

?>

6. Best Practices for Using get_the_terms()

To ensure your implementation is robust and maintainable, follow these best practices:

  1. Always Check for Errors: Use is_wp_error() to handle potential errors gracefully.
  2. Escape Output: Use esc_html() and esc_url() to sanitize output and prevent security vulnerabilities.
  3. Leverage Caching: Cache results when querying large datasets to improve performance.
  4. Keep Code Modular: Encapsulate your logic in reusable functions or shortcodes for better maintainability.

7. FAQs

What is the difference between get_the_terms() and get_the_term_list()?

get_the_terms() retrieves an array of term objects, giving you full control over how to display or manipulate the data. In contrast, get_the_term_list() directly outputs a formatted HTML string of terms as links. Use get_the_terms() for customization and get_the_term_list() for quick, pre-styled displays.

Can I use get_the_terms() with custom taxonomies?

Yes, absolutely! get_the_terms() works seamlessly with custom taxonomies. Simply specify the name of your custom taxonomy (e.g., ‘genre’ or ‘location’) as the second parameter. This flexibility makes it a powerful tool for organizing and displaying content tailored to your site’s unique structure.

How can I handle errors when using get_the_terms()?

Always check for errors by using is_wp_error() after calling get_the_terms(). If no terms are found or an issue occurs, the function may return false or a WP_Error object. Implementing proper error handling ensures your site remains functional and user-friendly, even when unexpected issues arise.

8. Conclusion

The get_the_terms() function is an indispensable tool for WordPress developers looking to display taxonomies effectively. By mastering its usage, you can create dynamic, user-friendly websites that are both visually appealing and SEO-optimized.

Whether you’re building a simple blog or a complex e-commerce platform, the techniques outlined in this guide will help you unlock the full potential of WordPress taxonomies. So go ahead—experiment with get_the_terms() and elevate your site’s content organization to the next level!

Have you implemented get_the_terms() in your projects?

WHAT'S YOUR TAKE?

Your email address will not be published. Required fields are marked *

We encompass a wide range of solutions, including eCommerce development, WordPress development, mobile app development, and digital marketing.

SUBSCRIBE NOW

Subscribe to AssaptR, our monthly look.
You have been successfully Subscribed! Oops! Something went wrong, please try again.

Contact info

Chat With Us
1
💭Need Help
Caught You! 👋🏻
Seeking For A Quick Assistance? We're Right Here!