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

如何实现显示子分类链接与名称而非父分类?

当然有可行的方案啦!具体实现得看你用的是什么技术栈或者CMS系统,我给你分几种常见场景说说:

1. WordPress 这类主流CMS场景

如果你用的是WordPress,实现起来很直接:

  • 可以用内置的get_terms()函数,指定parent参数为目标父分类的ID,就能精准获取该父分类下的所有子分类。示例代码如下:
    $child_terms = get_terms( array(
        'taxonomy' => 'category', // 替换成你实际用的分类法名称
        'parent'   => 5, // 替换成你的父分类ID
        'hide_empty' => false, // 是否显示无内容的空分类,按需调整
    ) );
    if ( ! empty( $child_terms ) && ! is_wp_error( $child_terms ) ) {
        echo '<ul>';
        foreach ( $child_terms as $term ) {
            echo '<li><a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>';
        }
        echo '</ul>';
    }
    
  • 要是用Elementor这类可视化编辑器,直接找「分类列表」组件,在设置里勾选「仅显示子分类」并指定对应的父分类,不用写代码就能搞定。
2. 自定义开发的网站场景(原生PHP/React/Vue等)

如果是自己开发的网站,核心思路是精准筛选子分类数据:

  • 后端层面:确保你的分类数据表有parent_id字段,查询时添加条件WHERE parent_id = 目标父分类ID,把符合条件的子分类数据返回给前端。
  • 前端层面:拿到后端返回的子分类数组后,循环渲染成链接列表即可。举个原生JS的例子:
    // 假设后端返回的子分类数据是这个数组
    const childCategories = [
        { id: 1, name: "子分类1", url: "/category/child1" },
        { id: 2, name: "子分类2", url: "/category/child2" }
    ];
    // 渲染到页面指定容器
    const container = document.getElementById('child-cats-container');
    const list = document.createElement('ul');
    childCategories.forEach(cat => {
        const li = document.createElement('li');
        const link = document.createElement('a');
        link.href = cat.url;
        link.textContent = cat.name;
        li.appendChild(link);
        list.appendChild(li);
    });
    container.appendChild(list);
    
3. 其他CMS场景(Shopify/Drupal)
  • Shopify:用Liquid模板语法,通过collection.children获取父分类的子分类,循环输出链接即可:
    {% assign parent_collection = collections.parent-category %}
    {% if parent_collection.children.size > 0 %}
        <ul>
            {% for child in parent_collection.children %}
                <li><a href="{{ child.url }}">{{ child.title }}</a></li>
            {% endfor %}
        </ul>
    {% endif %}
    
  • Drupal:借助Views模块,创建视图时选择「分类术语」,添加筛选条件「父分类等于指定值」,最后把输出格式设置为链接列表就完成了。

如果你的场景比较特殊,或者用的是其他工具,可以补充更多细节,我再帮你细化方案~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:27:52