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

WooCommerce自定义分类页(taxonomy-brand.php)添加产品分类筛选及重载咨询

在WooCommerce品牌分类页添加产品分类筛选器

1. 生成可点击的筛选链接

在你的taxonomy-brand.php模板中,获取产品分类术语后,为每个术语生成带筛选参数的链接——链接会保留当前品牌的查询条件,同时添加产品分类的筛选参数:

// 这里的 taxonomy 填产品分类的标识,比如默认的'product_cat'
$terms = get_terms([
    'taxonomy' => 'product_cat',
    'hide_empty' => true, // 只显示有产品的分类,避免空分类干扰用户
]);

// 获取当前页面的品牌术语对象
$current_brand = get_queried_object();

echo '<div class="product-category-filters">';
// 先加一个"全部"选项,点击回到品牌下所有产品
$all_url = get_term_link($current_brand);
echo '<a href="' . esc_url($all_url) . '" class="' . (empty($_GET['product_cat']) ? 'active' : '') . '">全部</a>';

foreach ($terms as $term) {
    // 构建筛选URL:保留当前品牌路径,追加产品分类参数
    $filter_url = add_query_arg(
        'product_cat',
        $term->slug,
        get_term_link($current_brand)
    );
    // 给当前选中的分类加高亮类
    $active_class = (isset($_GET['product_cat']) && $_GET['product_cat'] === $term->slug) ? 'active' : '';
    echo '<a href="' . esc_url($filter_url) . '" class="' . $active_class . '">' . esc_html($term->name) . '</a>';
}
echo '</div>';

2. 修改产品查询以应用筛选条件

在模板的产品循环之前,修改查询参数,结合当前品牌和筛选的产品分类:

// 获取当前品牌的ID
$current_brand_id = get_queried_object_id();

// 基础查询:当前品牌下的所有产品
$query_args = [
    'post_type' => 'product',
    'tax_query' => [
        [
            'taxonomy' => 'brand', // 替换成你的品牌 taxonomy 名称
            'field' => 'term_id',
            'terms' => $current_brand_id,
        ],
    ],
];

// 如果URL里有产品分类筛选参数,追加到查询条件
if (isset($_GET['product_cat']) && !empty($_GET['product_cat'])) {
    $query_args['tax_query'][] = [
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => sanitize_text_field($_GET['product_cat']),
        'operator' => 'AND', // 同时满足品牌和分类两个条件
    ];
}

// 初始化筛选后的产品查询
$filtered_products = new WP_Query($query_args);

// 产品循环
if ($filtered_products->have_posts()) {
    while ($filtered_products->have_posts()) {
        $filtered_products->the_post();
        // 调用WooCommerce默认产品模板
        wc_get_template_part('content', 'product');
    }
    // 显示分页
    woocommerce_pagination();
} else {
    echo '<p>没有找到相关产品</p>';
}

// 重置查询,避免影响后续内容
wp_reset_postdata();

3. 样式优化(可选)

给选中的筛选链接加高亮样式,让用户能直观看到当前筛选状态:

.product-category-filters a {
    margin-right: 10px;
    padding: 5px 10px;
    text-decoration: none;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.product-category-filters a.active {
    background-color: #21759b;
    color: #fff;
    border-color: #21759b;
}

设置完成后,用户点击筛选链接时,页面会带着筛选参数重新加载,展示符合「当前品牌+选中分类」的产品;点击「全部」则回到品牌下的完整产品列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:25:13