You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中按层级显示产品子分类与孙分类?

解决WooCommerce产品分类层级显示问题

原代码仅能展示一级子分类,无法识别三级及更深层级,核心问题是缺少递归遍历逻辑。以下是修改后的代码,通过递归函数实现层级化展示所有下级分类:

add_shortcode('child_category_list', 'get_child_category_list');

function get_child_category_list(){
    ob_start();
    
    // 仅在产品分类页面生效
    if( is_product_category() ) {
        $parent_term = get_queried_object();
        ?>
        <ul>
            <li>
                <a href="<?php echo get_term_link($parent_term); ?>"><?php echo $parent_term->name; ?></a>
                <?php render_category_hierarchy($parent_term->term_id); ?>
            </li>
        </ul>
        <?php
    }
    return ob_get_clean();
}

// 递归渲染分类层级
function render_category_hierarchy($parent_id){
    $child_categories = get_terms(array(
        'taxonomy' => 'product_cat',
        'parent' => $parent_id,
        'hide_empty' => false, // 如需隐藏空分类改为true
        'orderby' => 'name',
        'order' => 'ASC'
    ));

    if( !empty($child_categories) && !is_wp_error($child_categories) ){
        ?>
        <ul>
            <?php foreach($child_categories as $term): ?>
                <li>
                    <a href="<?php echo get_term_link($term); ?>"><?php echo $term->name; ?></a>
                    <?php render_category_hierarchy($term->term_id); // 递归调用渲染子分类 ?>
                </li>
            <?php endforeach; ?>
        </ul>
        <?php
    }
}

关键修改说明

  • 新增render_category_hierarchy递归函数,自动遍历当前分类的所有子分类,无论层级深度
  • 替换原get_term_children为get_terms,更灵活控制分类筛选(比如是否隐藏空分类)
  • 层级结构通过嵌套<ul>自动生成,三级分类会被包裹在二级分类的<li>内,保持正确层级
  • 保留原逻辑:仅在产品分类页面生效,默认显示当前父分类作为根节点

使用方式

将上述代码替换原短码函数,依然放在taxonomy-product-cat.php模板中,或添加到主题的functions.php文件中,即可通过短码[child_category_list]调用,或直接在模板中执行echo get_child_category_list();

内容的提问来源于stack exchange,提问作者libertarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 09:07:20