get_the_terms

Home » Functions » get_the_terms

Function Name: get_the_terms

If you ever need to retrieve the terms of a specific taxonomy assigned to a post, you can use the get_the_terms function in WordPress. It returns an array of terms assigned to the post in the specified taxonomy.

The function takes three parameters. The first one is the post ID, the second is the taxonomy name, and the third is an optional argument to retrieve the terms as objects instead of an array.

Here’s an example usage code:

$post_terms = get_the_terms( $post_id, 'category' );
if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
    foreach ( $post_terms as $term ) {
        echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
    }
}

In this example, we are retrieving the terms of the ‘category’ taxonomy assigned to the post with the ID of $post_id. We then check if there are any terms and if there are no errors. If there are terms, we loop through them and create a link to each term using the get_term_link function.

Overall, get_the_terms is a useful function for retrieving and displaying the terms assigned to a post.

Learn More on WordPress.org

WordPress snippets using the get_the_terms function

Register an account to save your snippets or go Pro to get more features.