WordPress Functions

WordPress: get_the_terms Function

24 October 2023

Imagine you’re building a WordPress site for a bustling bookstore. Each book (a custom post type) can belong to multiple genres (custom taxonomies), like “Fiction,” “Biography,” and “History.” You’ve crafted a special page to highlight books in certain genres, but how do you get the information about each book’s attached terms so you can properly filter content? That’s when WordPress’ get_the_terms function comes into play.

Identifying terms attached to a given post is straightforward with this user-friendly function. With just its post ID or object and taxonomy name, it digs deep into the post container element uncovering hidden mysteries like an archaeologist at an excavation site. It retrieves all attached terms from both default and custom post type taxonomies, effortlessly giving you the targeted data that allows for fine-tuning of your single post output. Whether it’s pulling up all books within ‘Mystery’ genre, or linking similar genres together through taxonomies terms links—WordPress get_the_terms is indispensable in bringing precise, relevant content straight to your readers.

Syntax

get_the_terms( $post, $taxonomy )

Parameters

  • $post (mixed) – The ID or object of the post for which to retrieve the attached terms.
  • $taxonomy (string) – The name of the taxonomy for which to retrieve the attached terms.

Return Value

The function returns an array of WP_Term objects representing the attached terms. If there are no terms attached to the post or if an error occurs, it returns false.

How get_the_terms function works

<?php
/**
* Retrieves the terms of the taxonomy that are attached to the post.
*
* @since 2.5.0
*
* @param int|WP_Post $post Post ID or object.
* @param string $taxonomy Taxonomy name.
* @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.
*/
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;
}
  1. The function first checks if the provided $post is valid by passing it through the get_post function. If it is not a valid post, the function returns false.
  2. Next, it attempts to retrieve the cached terms for the given post and taxonomy using the get_object_term_cache function. If there are no cached terms available, it calls wp_get_object_terms to fetch them from the database.
  3. If fetching the terms from the database is successful and there are no errors, it extracts an array of term IDs using wp_list_pluck and adds them to the cache using wp_cache_add.
  4. After retrieving or caching the terms, it applies any filters added by other functions using apply_filters, allowing developers to modify or manipulate the list of retrieved terms.
  5. Finally, if there are no terms available, it returns false; otherwise, it returns an array of WP_Term objects representing the attached terms.

Note that this function can be used to retrieve custom taxonomies associated with a post in order to display relevant information on a single post output page or generate links for custom taxonomy terms.

Usage Examples

Example: Get terms for the specific product and taxonomy

Let’s say you have developed a plugin that adds a custom post type called “Product” to your WordPress website. Each product has a custom taxonomy called “Product Category”. You want to retrieve the terms (categories) attached to a specific product and display them in the frontend.

<?php
// Assuming you have registered a custom post type 'product' and a custom taxonomy 'product_category' for it
// Get the ID of the product you want to retrieve terms for
$product_id = 123; // Replace 123 with the actual ID of your product post
// Retrieve the terms attached to the specified product
$terms = get_the_terms($product_id, "product_category");
if ($terms) {
foreach ($terms as $term) {
echo $term->name;
}
} else {
echo "No categories found.";
}

In this example:

  • You obtain the ID of the specific product you want to retrieve terms for. Replace 123 with the actual ID of your product.
  • The get_the_terms function is used to retrieve an array of WP_Term objects representing each term (category) attached to the specified product.
  • If terms are found, they are displayed in an unordered list ().
  • If no terms are found, a message “No categories found.” is displayed.

This allows you to display the categories of a specific product on its single page or anywhere else in your plugin’s template files.

To use this code inside your plugin, you can hook it into appropriate action or filter hooks like the_content, woocommerce_single_product_summary, or any other suitable hook depending on when and where you want to display the terms.

Example: Inside a Theme

Let’s say you have developed a custom WordPress theme for a blog website. You want to display the categories of each post in the sidebar. Here is how you can achieve that using the get_the_terms function.

<?php
// Assuming you are in the sidebar template file (e.g., sidebar.php) of your theme
// Get the current post object
global $post;
// Retrieve the terms (categories) attached to the current post
$terms = get_the_terms($post->ID, "category");
if ($terms) {
foreach ($terms as $term) {
echo $term->name;
}
} else {
echo "No categories found.";
}

In this example:

  • The global $post variable is used to get the current post object.
  • The get_the_terms function is used to retrieve an array of WP_Term objects representing each term (category) attached to the current post.
  • If terms are found, they are displayed in an unordered list ().
  • If no terms are found, a message “No categories found.” is displayed.

You can place this code in your theme’s sidebar template file (e.g., sidebar.php) or any other suitable template file where you want to display the categories. Make sure to use appropriate hooks like get_sidebar, dynamic_sidebar, or any other relevant WordPress hooks depending on how your theme is structured.

How do I get a custom taxonomy for a post in WordPress?

  • How do I get a custom taxonomy for a post in WordPress?
  • How do I get the taxonomy name in WordPress?
  • How do I get all taxonomy in WordPress?
  • How do I get post taxonomy?

How do I get a custom taxonomy for a post in WordPress?

To get a custom taxonomy for a post, use the ‘get_the_terms’ function. All you need is the post’s ID and your custom taxonomy’s name. For instance: $terms = get_the_terms($postId, ‘your_custom_taxonomy’); This will return an array of term objects associated with the post.

How do I get the taxonomy name in WordPress?

You can use WordPress’s built-in function ‘get_taxonomy’. Once you’ve retrieved the taxonomy object, you can find the name by accessing the ‘label’ property. Here’s a quick example: $taxonomy = get_taxonomy(‘your_taxonomy’); echo $taxonomy->label;

How do I get all taxonomy in WordPress?

If you’re trying to retrieve all taxonomies associated with your WordPress site, ‘get_taxonomies’ function comes handy. There’s no need to provide any arguments for this function: $taxonomies = get_taxonomies(); This will return an array of registered taxonomies.

How do I get post taxonomy?

To get the taxonomy of a post, you can use the ‘get_post_taxonomies’ function. You just have to pass the post object or the post ID. This example will get you started: $taxonomies = get_post_taxonomies($post);

Leave a Reply

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

Array

Some of Our Clients

Join clients who enjoy 96% satisfaction

Schedule a Free Strategy Call with a WordPress Expert