猿问

我正在尝试让 woocommerce 列出 (ul) 子类别以显示在主要类别下

我想列出 (ul) 类别及其各自的子类别(如果有)。如何使用下面的代码在 archive-product.php 中包含子类别 通过下面的代码,我将获得同一级别的类别和子类别。餐具、玻璃器皿和扁平餐具是餐桌设置的子类别, 在此处输入图像描述

<?php


$args = array(

    'taxonomy'          => 'product_cat',

    'hide_empty'        => false,

    );

$result = get_terms( $args );

?>

<ul class="list-unstyled">


            <?php

                foreach ( $result as $cat ) {

                    if ( 'Uncategorized' !== $cat->name ) {

                    $term_link = get_term_link( $cat, 'product_cat' );

                    $cat_thumb_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );

                    $shop_catalog_img_arr = wp_get_attachment_image_src( $cat_thumb_id, 'shop_catalog' );

                    $cat_img = $shop_catalog_img_arr[0];

                        ?>

                    

                    

                        <li><a href="<?php echo $term_link; ?>">

                                <?php echo $cat->name; ?> 

                            </a></li>

                        

                    


                <?php

                    }

                }

                ?>


                    </ul>


慕尼黑5688855
浏览 123回答 1
1回答

米琪卡哇伊

<li>如果术语有父类别并且因此是子类别,则可以将类别设置为。通过这个类,您可以设置它在 CSS 中的外观,并使其看起来像“子类别”:<!-- code before --><li <?php if( $cat->parent !== 0 ) { echo 'class="child_cat" '; } ?>>&nbsp; &nbsp; <a href="<?php echo $term_link; ?>">&nbsp; &nbsp; &nbsp; &nbsp; <?php echo $cat->name; ?>&nbsp; &nbsp; </a></li><!-- code after -->当$cat有父级使用$cat->parent该类时将被添加。在 style.css 中,您可以调整样式:.child_cat { font-size: 0.9rem; padding-left: 2.5rem; }这样子类别将具有较小的字体大小和左侧的填充。编辑:您希望子类别在其各自的父类别下方列出。我建议使用get_terms两次,一次用于接父母,另一次用于接孩子。循环遍历它们。您的代码可以如下所示:<ul class="list-unstyled"><?php$parent_arguments = array('parent' => 0, 'hide_empty' => true );$parent_terms = get_terms('product_cat', $parent_arguments );foreach ( $parent_terms as $parent_term ) {&nbsp; &nbsp; echo '<li><a href="'.get_term_link( $parent_term, "product_cat" ).'">'.$parent_term->name.'</a></li>'; // Parent term&nbsp; &nbsp; $child_arguments = array( 'parent' => $parent_term->term_id, 'hide_empty' => true );&nbsp; &nbsp; $child_terms = get_terms( 'product_cat', $child_arguments );&nbsp; &nbsp; echo '<ul>';&nbsp; &nbsp; &nbsp; &nbsp; foreach( $child_terms as $child_term ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo '<li class="child_cat"><a href="'.get_term_link( $child_term, "product_cat" ).'">'.$child_term->name.'</a></li>'; // Child term&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; echo '</ul>';} ?></ul>
随时随地看视频慕课网APP
我要回答