在WooCommerce 6.9.1产品页显示优惠券折扣价的代码修复请求
WooCommerce 6.9.1 产品页展示优惠券折扣价代码修复
问题说明
使用适用于WooCommerce 3.x的旧代码在6.9.1版本中运行时,出现语法错误:syntax error, unexpected '}', expecting end of file,同时部分旧API在新版本中已不兼容。
旧代码问题分析
- 代码末尾多了一个冗余的
},导致语法结构不匹配 - 部分旧版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
相关产品推荐
相关产品推荐

