I'm using the WooCommerce shopping cart plugin and have written my own theme with file overrides for the default WooCommerce templates, in order for more control. So I created a sidebar from scratch that lists out all the product categories. It works great:
<ul class="sidebar-list">
<?php
$all_categories = get_categories( 'taxonomy=product_cat&hide_empty=0&hierarchical=1' );
foreach ($all_categories as $cat) {
echo '<li><a href="'. get_term_link($cat->slug, 'product_cat') .'"><span>'. $cat->name .'</span></a>';
}
?>
</ul>
But, the above foreach
loop does not output any sort of "current category" attribute (like a class on the list item). So I've attempted to write some PHP that grabs the current product category and compares it inside the foreach loop to the category being displayed and if they match, add a "current" class to the list item.
<ul class="sidebar-list">
<?php
$all_categories = get_categories( 'taxonomy=product_cat&hide_empty=0&hierarchical=1' );
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->term_id;
break;
}
foreach ($all_categories as $cat) {
echo '<li class="';
if ( $product_cat == $cat->id ) {
echo "current";
}
echo '"><a href="'. get_term_link($cat->slug, 'product_cat') .'"><span>'. $cat->name .'</span></a>';
}
?>
</ul>
As you might gather from me posting this here, it does not work.
I know I have a problem in that I'm not even able to grab the $cat->id
, because if I echo it out on its own I get nothing. Seems all I have access to is the $cat->name
and $cat->slug
.
And on top of that, I'm sure my logic is flawed too. Can someone get me headed in the right direction here?
Thank you, thank you, thank you!