【问题标题】:Woocommerce - add extra class to category if has subcategoriesWoocommerce - 如果有子类别,则向类别添加额外的类
【发布时间】:2021-01-30 16:22:26
【问题描述】:

如果该类别有子类别,我需要在<li> 元素中添加像dropdown 这样的额外类:

<ul class="departments__links">

    <?php
    $taxonomy     = 'product_cat';
    $orderby      = 'name';  
    $show_count   = 0;      // 1 for yes, 0 for no
    $pad_counts   = 0;      // 1 for yes, 0 for no
    $hierarchical = 1;      // 1 for yes, 0 for no  
    $title        = '';  
    $empty        = 0;

    $args = array(
        'taxonomy'     => $taxonomy,
        'orderby'      => $orderby,
        'show_count'   => $show_count,
        'pad_counts'   => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li'     => $title,
        'hide_empty'   => $empty
    );

    $all_categories = get_categories( $args );

    foreach ($all_categories as $cat) {
        if ($cat->category_parent == 0) {
            $category_id = $cat->term_id;

            echo '<li class="departments__item EXTRA-CLASS-HERE"><a href="'. get_term_link( $cat->slug, 'product_cat' ) .'" class="departments__item-link">'. $cat->name . '</a></li>';

        }       
    }
    ?>          

</ul>

此代码来自:https://stackoverflow.com/a/21012252/9598872

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    你可以这样使用

    <?php
    $taxonomy     = 'product_cat';
    $orderby      = 'name';  
    $show_count   = 0;      // 1 for yes, 0 for no
    $pad_counts   = 0;      // 1 for yes, 0 for no
    $hierarchical = 1;      // 1 for yes, 0 for no  
    $title        = '';  
    $empty        = 0;
    
    $args = array(
        'taxonomy'     => $taxonomy,
        'orderby'      => $orderby,
        'show_count'   => $show_count,
        'pad_counts'   => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li'     => $title,
        'hide_empty'   => $empty
    );
    
    $all_categories = get_categories( $args );
     $extraclass = '';
    foreach ($all_categories as $cat) {
        if ($cat->category_parent == 0) {
            $category_id = $cat->term_id;
    
            $children = get_terms( $taxonomy, array(
            'parent'    => $category_id,
            'hide_empty' => false
            ) );
            if($children) { 
               $extraclass = "dropdown";
            }else{
             $extraclass = "";
             }
    
            echo '<li class="departments__item '.$extraclass.'"><a href="'. get_term_link( $cat->slug, 'product_cat' ) .'" class="departments__item-link">'. $cat->name . '</a></li>';
    
        }       
    }
    ?>          
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2015-09-18
      • 1970-01-01
      • 2021-12-05
      • 2016-09-20
      • 1970-01-01
      相关资源
      最近更新 更多