PHP / Wordpress - 将属性添加到无序列表中的当前类别


PHP/Wordpress - add attribute to current category in unordered list

>我正在使用WooCommerce购物车插件,并为默认的WooCommerce模板编写了自己的主题,其中包含文件覆盖,以便进行更多控制。所以我从头开始创建了一个侧边栏,列出了所有产品类别。效果很好:

<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>

但是,上面的foreach循环不会输出任何类型的"当前类别"属性(如列表项上的类)。因此,我尝试编写一些PHP,以获取当前产品类别并将其在foreach循环中与正在显示的类别进行比较,如果它们匹配,则向列表项添加一个"当前"类。

<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>

正如您可能从我这里发布此内容所收集的那样,它不起作用。

我知道我有一个问题,我甚至无法抓住$cat->id,因为如果我自己回声,我什么也得不到。似乎我只能访问$cat->name$cat->slug.

最重要的是,我确信我的逻辑也有缺陷。有人能让我朝着正确的方向前进吗?

谢谢,谢谢

,谢谢!

您可以使用wp_list_categories

仅在存档/类别页面上将 CSS 类current-cat添加到活动类别:

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

将 CSS 类current-cat添加到 get_the_category() 返回结果的所有页面上的活动类别:

<?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);
?>