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

在WooCommerce 6.9.1产品页显示优惠券折扣价的代码修复请求

WooCommerce 6.9.1 产品页展示优惠券折扣价代码修复

问题说明

使用适用于WooCommerce 3.x的旧代码在6.9.1版本中运行时,出现语法错误:syntax error, unexpected '}', expecting end of file,同时部分旧API在新版本中已不兼容。

旧代码问题分析

  1. 代码末尾多了一个冗余的},导致语法结构不匹配
  2. 部分旧版WooCommerce函数参数或逻辑已更新,直接使用会出现兼容性问题

修复并适配后的代码

这段代码需要挂载到woocommerce_get_price_html过滤器中使用,完整实现如下:

add_filter( 'woocommerce_get_price_html', 'display_product_coupon_discounted_price', 10, 2 );
function display_product_coupon_discounted_price( $price, $product ) {
    // 仅在产品页面且购物车有优惠券时生效
    if ( is_product() && WC()->cart && WC()->cart->has_discount() ) {
        $values = array(
            'data'      => $product,
            'quantity'  => 1
        );
        $coupons = WC()->cart->get_coupons();
        $_price = $product->get_price();
        $undiscounted_price = $_price;

        if ( ! empty( $coupons ) ) {
            foreach ( $coupons as $code => $coupon ) {
                // 适配新版本的优惠券有效性验证
                if ( $coupon->is_valid() ) {
                    $is_valid_for_product = $coupon->is_valid_for_product( $product );
                    $is_valid_for_cart = $coupon->is_valid_for_cart();

                    if ( $is_valid_for_product || $is_valid_for_cart ) {
                        $calc_sequentially = 'yes' === get_option( 'woocommerce_calc_discounts_sequentially', 'no' );
                        $discount_amount = $coupon->get_discount_amount( $calc_sequentially ? $_price : $undiscounted_price, $values, true );
                        $discount_amount = min( $_price, $discount_amount );
                        $_price = max( $_price - $discount_amount, 0 );
                    }
                }
                if ( $_price <= 0 ) {
                    break;
                }
            }

            if ( $product->get_price() > 0 && $undiscounted_price !== $_price ) {
                $display_undiscounted = wc_get_price_to_display( $product, array( 'price' => $undiscounted_price ) );
                $display_discounted = wc_get_price_to_display( $product, array( 'price' => $_price ) );
                $price = wc_format_sale_price( $display_undiscounted, $display_discounted ) . $product->get_price_suffix();
            }
        }
    }
    return $price;
}

关键修复点

  • 移除末尾冗余的},修复语法错误
  • 调整优惠券有效性验证逻辑,适配WooCommerce 6.x版本的is_valid_for_product和is_valid_for_cart函数
  • 优化价格显示处理逻辑,确保价格格式化符合新版本规范
  • 添加is_product()判断,确保仅在产品页面生效
  • 增加WC()->cart存在性检查,避免未初始化导致的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:05:23