1

I'm currently using get_terms to list terms of a certain taxonomy. I would like to add a class to the term currently being queried via the archive template.

I tried putting together the below code but this bizarrely results in the class being applied to not just the current term being queried but every term AFTER it as well. I've tried comparing the slugs, ids and names of $term and $currentterm - all of which output correctly.

$terms = get_terms('MYTAX');
$currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
foreach ($terms as $term) {
  if($currentterm->slug == $term->slug) $class = "live";
  echo '<li class="'. $class .'"><a href="http://website.com/?MYTAX='. $term->slug .'">' . $term->name . '</a></li>';
}
3

Try this instead:

$terms = get_terms('MYTAX'); 
$currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 
foreach ($terms as $term) {
     $class = $currentterm->slug == $term->slug ? 'live' : '' ;
     echo '<li class="'. $class .'"><a href="http://website.com/?MYTAX='. $term->slug .'">' . $term->name . '</a></li>'; 
}

Basically you just need to reset your $class variable back to an empty string after your conditional has returned false, otherwise it will continue to remain true. Its seems odd, but once you know how to handle it, its all good.

  • Thanks Michael, unfortunately the ? is throwing expecting T_STRING or T_VARIABLE or '{' or '$' – rspny Jan 24 '14 at 21:48
  • It's because i left a syntax error in, my bad, just about to edit answer. – user10106 Jan 24 '14 at 21:52
  • Ahh, I see. That is really weird. It works though. Thank you! – rspny Jan 24 '14 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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