I want to output all the terms in my custom taxonomy and at the same time add a class to any of these that are attached to the current post.

I'm doing this in a custom shortcode that displays on each single post page.

I've used get_terms() to show all the terms in the taxonomy but I can't work out how to check if each term is attached to the current post.

$terms = get_terms( array(
    'taxonomy' => 'package',
    'hide_empty' => false
) );

if (!empty($terms) && ! is_wp_error( $terms )) {
  echo '<ul>';
  foreach ($terms as $term) {
    echo '<li>' . $term->name . '</li>';
  echo '</ul>';  
  • Where did you put the code? In the taxonomy template, e.g. taxonomy-my_tax.php? And what is the "current post"? Where does it come from?
    – Sally CJ
    Sep 30, 2020 at 19:52

1 Answer 1


how to check if each term is attached to the current post

You can do that using has_term() which defaults to checking on the current post in the main loop, hence you can omit the third parameter (the post ID).

So for example in your case:

$class = has_term( $term->term_id, $term->taxonomy ) ? 'active' : ''; // like this
//$class = has_term( $term->term_id, 'package' ) ? 'active' : '';     // or this

echo '<li class="' . $class . '">' . $term->name . '</li>';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.