PHP/Wordpress - add attribute to current category

2019-08-31 03:53发布

问题:

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!

回答1:

You can use wp_list_categories:

Adds CSS class current-cat to the active category only on archive/category pages:

<?php
    $args = array(
        'taxonomy' => 'product_cat',
        'hide_empty' => 0,
        'hierarchical' => 1
    );
    wp_list_categories($args);
?>

Adds CSS class current-cat to the active category on all pages where get_the_category() returns a result:

<?php
    $category = get_the_category();
    $current_category_ID = isset($category->cat_ID) ? $category->cat_ID : 0;
    $args = array(
        'taxonomy' => 'product_cat',
        'hide_empty' => 0,
        'hierarchical' => 1,
        'current_category' => $current_category_ID
    );
    wp_list_categories($args);
?>