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

如何修改PHP代码为WordPress产品分类菜单新增二级子分类嵌套

修改方案

你只需要在原有一级子分类的遍历逻辑中,新增一层二级子分类的判断和输出即可,修改后的完整代码如下:

<?php
// 初始化变量避免PHP未定义警告
$output = '';
$taxonomies = get_terms(array(
    'taxonomy' => 'product_cat',
    'hide_empty' => true
));

if (!empty($taxonomies)) :
    foreach ($taxonomies as $category) {
        if ($category->parent == 0) {
            $output .= '<div class="menu_item">';
            if (get_term_children($category->term_id, 'product_cat')) {
                $output .= '<div class="parent_item"><a href="' . get_term_link($category) . '">' . $category->name . '</a></div>';
                $output .= '<div class="sub_menu">';
                foreach ($taxonomies as $subcategory) {
                    if ($subcategory->parent == $category->term_id) {
                        $output .= '<div class="sub_item">';
                        $output .= '<a href="' . get_term_link($subcategory) . '">' . $subcategory->name . '</a>';
                        
                        // 新增二级子分类输出逻辑
                        $has_child = false;
                        $child_output = '<div class="2sub_item">';
                        foreach ($taxonomies as $child_category) {
                            if ($child_category->parent == $subcategory->term_id) {
                                $has_child = true;
                                $child_output .= '<a href="' . get_term_link($child_category) . '">' . $child_category->name . '</a>';
                            }
                        }
                        $child_output .= '</div>';
                        // 仅当存在二级子分类时输出对应容器
                        if ($has_child) {
                            $output .= $child_output;
                        }
                        
                        $output .= '</div>';
                    }
                }
                $output .= '</div>';
            }
            $output .= '</div>';
        }
    }
    echo $output;
endif;
?>

调整说明

  • 保留原有代码所有功能逻辑,仅新增二级子分类遍历部分,筛选父ID等于当前一级子分类ID的分类项
  • 新增了空判断逻辑,避免某一级子分类没有二级分类时输出空的2sub_item容器
  • 输出结构完全匹配你提供的期望HTML格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:45:02