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

自定义Taxonomy下拉菜单层级显示问题代码修正求助

修复自定义分类法下拉菜单的层级展示问题

原代码的问题在于直接平铺输出所有分类,没有区分父级与子级的层级关系,也没有按层级排序。下面是修正后的代码,核心是通过递归遍历分类层级,给子分类添加缩进标识,同时确保分类按层级顺序排列:

<form style="width: 100%;">
    <?php
    // 获取city分类法下的所有层级分类,按名称排序
    $categories = get_terms(array(
        'taxonomy' => 'city',
        'hide_empty' => true, // 只显示有内容的分类,对应原代码的count>0
        'hierarchical' => true,
        'orderby' => 'name',
        'order' => 'ASC'
    ));

    $select = "<select style='margin-top: 15px; width: 100%; height: 30px; font-family : Glegoo; font-size: 12pt' name='cat' id='cat' class='postform'>\n";
    $select .= "<option style='height: 10px; font-weight: bold' value='-1'> SELECT ANOTHER CITY </option>\n";

    // 递归生成带层级的分类选项
    function generateHierarchicalOptions($terms, $parent_id = 0, $depth = 0) {
        $options = '';
        $indent = str_repeat('&emsp;', $depth); // 用全角空格做层级缩进,可替换为---等符号
        foreach ($terms as $term) {
            if ($term->parent == $parent_id) {
                $options .= "<option value='" . $term->slug . "'>" . $indent . $term->name . "</option>\n";
                // 递归处理当前分类的子分类
                $options .= generateHierarchicalOptions($terms, $term->term_id, $depth + 1);
            }
        }
        return $options;
    }

    // 调用递归函数生成层级选项
    $select .= generateHierarchicalOptions($categories);
    $select .= "</select>";

    echo $select;
    ?>

    <script type="text/javascript"><!--
        var dropdown = document.getElementById("cat");

        function onCatChange() {
            if (dropdown.options[dropdown.selectedIndex].value != -1) {
                location.href = "<?php echo home_url();?>/city/" + dropdown.options[dropdown.selectedIndex].value + "/";
            }
        }

        dropdown.onchange = onCatChange;
    --></script>
</form>

关键修改说明:

  • 替换get_categories为get_terms(更适配自定义分类法,参数配置更直观),新增hierarchical、orderby参数确保分类按层级和名称排序
  • 新增递归函数generateHierarchicalOptions,遍历分类的父/子关系,给不同层级的子分类添加对应缩进,直观区分层级
  • 原JS跳转逻辑功能正常,无需修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:55:23