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

如何在WooCommerce中创建带筛选功能的促销商品归档页?

解决WooCommerce促销商品归档页筛选重定向问题

问题根源

OnSale Page for WooCommerce因为停止维护,它生成的促销归档页没有正确适配WooCommerce的筛选查询参数逻辑,导致分类、属性筛选操作触发后直接跳转到默认商店页,这是这类废弃插件常见的兼容性问题。

替代解决方案(无需依赖第三方插件)

方法1:自定义促销商品归档模板

  • 在你的主题子主题(务必用子主题,避免主题更新丢失修改)的woocommerce目录下,新建archive-product-onsale.php文件;如果主题没有woocommerce目录,就在子主题根目录新建自定义页面模板文件。
  • 写入以下代码,实现只加载促销商品的归档页逻辑:
<?php
/**
 * Template Name: 促销商品归档页
 */
get_header();

// 构建促销商品查询参数
$sale_query_args = array(
    'post_type'      => 'product',
    'posts_per_page' => get_option('posts_per_page'),
    'meta_query'     => array(
        array(
            'key'     => '_sale_price',
            'value'   => 0,
            'compare' => '>',
            'type'    => 'numeric'
        )
    ),
    // 保留WooCommerce默认筛选参数
    'tax_query'      => isset($_GET['taxonomy']) ? wc_get_product_taxonomy_query() : array(),
);

$sale_products = new WP_Query($sale_query_args);

if ($sale_products->have_posts()) :
    woocommerce_product_loop_start();
    while ($sale_products->have_posts()) : $sale_products->the_post();
        wc_get_template_part('content', 'product');
    endwhile;
    woocommerce_product_loop_end();
    woocommerce_pagination();
else :
    do_action('woocommerce_no_products_found');
endif;

wp_reset_postdata();
get_footer();
?>
  • 后台新建页面,选择这个“促销商品归档页”模板发布,此时页面会加载所有促销商品,且WooCommerce官方的分类、属性筛选小工具会自动适配该页面,筛选操作不会再跳转到商店页。

方法2:短代码+自定义筛选逻辑

  • 用WooCommerce原生短代码[products on_sale="true"]在页面展示促销商品,然后在子主题的functions.php中添加以下代码,让筛选参数能被短代码识别:
// 适配促销商品短代码的筛选逻辑
add_filter('woocommerce_shortcode_products_query', 'enable_sale_products_filter', 10, 3);
function enable_sale_products_filter($query_args, $atts, $loop_name) {
    if ($atts['on_sale'] !== 'true') return $query_args;

    // 处理分类筛选参数
    if (!empty($_GET['product_cat'])) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => sanitize_text_field($_GET['product_cat'])
        );
    }

    // 处理属性筛选(示例为颜色属性,替换为你的实际属性名,格式为pa_属性名)
    if (!empty($_GET['pa_color'])) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'pa_color',
            'field'    => 'slug',
            'terms'    => sanitize_text_field($_GET['pa_color'])
        );
    }

    return $query_args;
}
  • 这样在使用短代码的页面上,官方筛选小工具的参数会被正确传递,筛选结果直接在当前页面展示,不会跳转。

注意事项

  • 只使用WooCommerce官方的“产品分类”“产品属性”小工具,第三方小工具可能存在兼容性问题。
  • 修改代码前做好备份,避免操作失误导致站点异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:22:03