Ouput Custom Taxonomy Terms in a Post

If you have created a custom taxonomy and linked it to a custom post type and want to output any terms used for that post in the single post view you can use the_terms

the_terms

<?php the_terms( int $post_id, string $taxonomy, string $before = '', string $sep = ', ', string $after = '' ); ?>

In a PHP template you can use…

<p><?php the_terms( get_the_id(), 'colour_category', __( "<label>Colour:</label> " ), ", ","." ); ?></p>

The current post id is referenced, the custom taxonomy is checked – col0ur_category in this instance, a text prefix is output followed by the terms used in a comma separated string of text, the $before and $sep are used in the example as well as the $after parameter which ends the term list with a full stop.  The terms are links which are linked back to the taxonomy archive page.

Changed the marked text to your custom taxonomy and add a text prefix swapping the above used <label>Colour:</label>

 

get_the_terms_list

Similarly is get_the_terms_list which is almost the same.

<?php get_the_term_list( $id, $taxonomy, $before, $sep, $after ) ?>

So in PHP you can use…

<?php echo get_the_term_list( get_the_id(), 'colour_category',  "<h3>Colours</h3><ul><li>","</li>><li>" ,"</li></ul>" ); ?>

Here using get_the_term_list, the passed in parameters are the current post id, the taxonomy followed by some HTML mark up which is the before HTML, the separating HTML followed by the ending HTML – the separating HTML allows the list mark up to join the beginning and end mark up.

get_the_terms

Another function that can be utilised is get_the_terms

<?php get_the_terms( int $post, string $taxonomy ); ?>

Continuing with the same example

<?php $cat_array = ( get_the_terms( get_the_ID(), 'colour_category') ); 
    
    foreach ($cat_array as $cat ) : 
        echo $cat->name . ' '; 

    endforeach; 
?>

With get_the_terms the terms are not output as links which may be the attraction of using this method.

The taxonomy is assigned to an array with a foreach loop running through it and outputting each term followed by a space.

To comma separate the terms with a full stop at the end of the last term the same function is used with a different approach.

<?php 

    $cat_array = ( get_the_terms( get_the_ID(), 'colour_category') ); 

    $cat_str = array(); 
    
    foreach ($cat_array as $cat) {
        
        $cat_str[] = $cat->name;

    }
    echo implode(", ",$cat_str) . '.'; 

?>

A second array is created with the foreach loop output stored in it, then that array is output with implode with a comma for each term and a full stop at the end.

1 Comments

  1. Ajay on May 26, 2021 at 11:08 pm

    Thank you, spent 2 hours figuring it out :)

Leave all Comment