0

I'm trying to figure out how to add an "active" class to a menu link when in that category.

For example, if in the Shirts Category, I would like it to have an active class so I can style it differently:

Shirts | Jeans | Shoes

Here's the code I'm currently using:

function show_parent_categories( $args = array() ) {

$args = array(  
    'hierarchical' => 1,
    'show_option_none' => '',
    'hide_empty' => 0,
    'parent' => $category->term_id,
    'taxonomy' => 'product_cat'
);

$product_categories = get_terms( 'product_cat', $args );

$count = count($product_categories);
 if ( $count > 0 ){
 echo "<div id='main-categories-wrapper'><ul id='main-categories'>";
 foreach ( $product_categories as $product_category ) {
   echo '<li><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</li>';

 }
 echo "</ul></div>";
}
}
0

1 Answer 1

-1

You can use is_category() You can check the documentation here

function show_parent_categories( $args = array() ) {

$args = array(  
    'hierarchical' => 1,
    'show_option_none' => '',
    'hide_empty' => 0,
    'parent' => $category->term_id,
    'taxonomy' => 'product_cat'
);

$product_categories = get_terms( 'product_cat', $args );

$count = count($product_categories);
 if ( $count > 0 ){
 echo "<div id='main-categories-wrapper'><ul id='main-categories'>";
 foreach ( $product_categories as $product_category ) {
   echo '<li><a class="'.(is_category($product_category->slug)?'active':'').'" href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</li>';

 }
 echo "</ul></div>";
}
}
4
  • Thanks. I'm getting some sort of syntax error though from that line. Do you know what might be causing it?
    – Amanda
    Oct 1, 2016 at 15:59
  • When I run it through a php validator it says "Parse error: syntax error, unexpected ')', expecting ',' or ';' in your code"
    – Amanda
    Oct 1, 2016 at 16:07
  • I have made the changes, i have added an extra bracket, let me know if the answer works for you. If it works please mark my answer. Thanks.
    – tam
    Oct 2, 2016 at 17:52
  • It doesn't give an error, but it also doesn't produce a class either. Someone else suggested adding 'is_tax( 'product_cat', $product_category->slug )' which does add a class. However I'm wondering if it's possible to have the active class stay on the category link when you're in a subcategory of that category as well.
    – Amanda
    Oct 2, 2016 at 18:08

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.