Adding active/current class to get_terms list

I have a list of terms I’m displaying using “get_terms”. Each term is linked so if the user clicks it, they go to the term archive page.

 <?php $terms = get_terms('category');t
 echo '<ul>';
 foreach ($terms as $term) {
 echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>';
 }
 echo '</ul>';
 ?>

However, I would like to know if there’s a way to add an “active” class to each term link if user goes to the term archive page.

Thanks a lot for your help,

3 Answers
3

Run a conditional check in the foreach loop using is_category($term-name)

Assign a class variable to active if it’s the same as $term->name

$terms = get_terms( 'category' );
echo '<ul>';
foreach ( $terms as $term ) {
    $class = ( is_category( $term->name ) ) ? 'active' : ''; // assign this class if we're on the same category page as $term->name
    echo '<li><a href="' . get_term_link( $term ) . '" class="' . $class . '">' . $term->name . '</a></li>';
}
echo '</ul>';

Leave a Comment