Woocommerce-如果有子类别,则在类别中添加额外的类别

时间:2020-10-16 06:47:14

标签: php wordpress woocommerce

如果此类别具有子类别,我需要向dropdown元素添加诸如<li>之类的额外类:

<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

1 个答案:

答案 0 :(得分: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>';

    }       
}
?>          
相关问题