在WooCommerce订单详情和邮件通知中添加优惠券名称及折扣百分比
原有代码核心错误点
$order->get_used_coupons()返回的是已使用优惠券的编码字符串数组,不是优惠券对象,无法直接调用discount_type、coupon_amount这类属性,需要先通过编码实例化WC_Coupon对象获取对应属性- 语法错误:
implode( ', ', $applied_coupons '<p>...' )缺少参数分隔的逗号,且逻辑错误:如果存在多张优惠券,你原来的写法会把折扣比例统一加在所有优惠券末尾,而不是对应到每张百分比类型的优惠券上 - 变量未定义风险:如果没有百分比类型的优惠券,
$applied_coupons_percentage变量未初始化,直接使用会抛出PHP警告
修正后完整代码
add_filter( 'woocommerce_get_order_item_totals', 'add_coupons_codes_line_to_order_totals_lines', 10, 3 ); function add_coupons_codes_line_to_order_totals_lines( $total_rows, $order, $tax_display ) { // 没有使用优惠券直接返回 if( sizeof( $order->get_used_coupons() ) == 0 ) return $total_rows; $new_total_rows = []; foreach($total_rows as $key => $total ){ $new_total_rows[$key] = $total; if( $key == 'discount' ){ $applied_coupon_codes = $order->get_used_coupons(); $processed_coupons = []; // 遍历每张优惠券单独处理 foreach ($applied_coupon_codes as $code) { $coupon = new WC_Coupon($code); $coupon_text = $code; // 百分比类型优惠券追加折扣比例 if($coupon->get_discount_type() == 'percent' && $coupon->get_amount()){ $coupon_text .= sprintf(' (%d%% OFF)', $coupon->get_amount()); } $processed_coupons[] = $coupon_text; } // 插入优惠券行 $new_total_rows['coupon_codes'] = array( 'label' => __('Applied coupons:', 'woocommerce'), 'value' => implode(', ', $processed_coupons), ); } } return $new_total_rows; }
代码逻辑说明
- 先获取所有已使用优惠券编码,遍历每张编码实例化优惠券对象
- 单独判断每张优惠券的类型,如果是百分比折扣,就把折扣比例拼到对应优惠券名称后面
- 所有优惠券处理完成后再用逗号拼接展示,兼容多张混合类型优惠券同时使用的场景
- 统一使用WooCommerce官方提供的
get_discount_type()、get_amount()方法获取优惠券属性,兼容高版本WooCommerce
内容的提问来源于stack exchange,提问作者Wanderlust Consulting
相关产品推荐
相关产品推荐

