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

WooCommerce单商品页仅显示指定父分类下子分类的实现方法

WooCommerce单商品页仅展示指定父分类下所属子分类实现方案

已完成wc_get_product_category_list钩子在商店归档页的挂载配置时,要实现单商品页仅展示特定父分类(如Artist)下子分类的效果,直接通过同钩子增加页面判断做过滤即可,不会影响归档页原有展示逻辑。

实现逻辑

仅在单商品页触发过滤逻辑:

  • 拉取当前商品关联的所有商品分类
  • 逐个判断分类是否归属目标父分类的子级
  • 剔除不符合要求的分类项,重新拼接分类列表输出

可直接使用的代码

将以下代码添加到子主题的functions.php文件,或者通过代码片段插件插入即可生效:

add_filter( 'wc_get_product_category_list', 'custom_filter_single_product_subcats', 99, 3 );
function custom_filter_single_product_subcats( $category_list, $product_id, $args ) {
    // 非单商品页直接返回原有内容,不影响归档页配置
    if ( ! is_product() ) {
        return $category_list;
    }

    // 配置项:替换为你要展示子分类对应的父分类参数,slug和ID二选一即可
    $target_parent_slug = 'artist'; // 父分类的slug,对应Artist分类
    // $target_parent_id = 15; // 若用ID判断,注释上一行,替换为实际父分类ID即可

    // 获取当前商品绑定的所有商品分类
    $product_terms = get_the_terms( $product_id, 'product_cat' );
    if ( empty( $product_terms ) || is_wp_error( $product_terms ) ) {
        return '';
    }

    $valid_terms = [];
    foreach ( $product_terms as $term ) {
        // 获取当前分类的所有祖先分类ID
        $ancestor_ids = get_ancestors( $term->term_id, 'product_cat' );
        $is_valid = false;

        if ( isset( $target_parent_slug ) ) {
            $parent = get_term_by( 'slug', $target_parent_slug, 'product_cat' );
            if ( $parent && ! is_wp_error( $parent ) ) {
                // 兼容多级子分类场景,只要是目标父分类下的子/孙分类都会被保留
                $is_valid = in_array( $parent->term_id, $ancestor_ids ) || $term->parent === $parent->term_id;
            }
        } else {
            $is_valid = in_array( $target_parent_id, $ancestor_ids ) || $term->parent === $target_parent_id;
        }

        if ( $is_valid ) {
            $valid_terms[] = $term;
        }
    }

    if ( empty( $valid_terms ) ) {
        return '';
    }

    // 按原有格式拼接分类链接
    $term_links = [];
    foreach ( $valid_terms as $term ) {
        $term_links[] = sprintf(
            '<a href="%s" rel="tag">%s</a>',
            esc_url( get_term_link( $term, 'product_cat' ) ),
            esc_html( $term->name )
        );
    }

    return implode( $args['sep'], $term_links );
}

调整说明

  • 如果子分类都是直接挂载在目标父分类下的一级子分类,没有多层级分类,可以删除get_ancestors相关判断,仅校验$term->parent是否匹配目标父分类ID即可,运行效率更高
  • 如果需要展示多个父分类下的子分类,把目标父类参数改为数组,调整判断逻辑遍历匹配即可
  • 代码钩子优先级设为99,不会和之前挂载的归档页分类展示逻辑冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 04:18:20