Output all terms in a custom taxonomy and add a “active” class only to the ones attached to the current post

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>';  
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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>';


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x