WooCommerce特定商品购买生成优惠券:代码问题排查求助
代码错误排查与修正
存在的问题:
- 赋值/比较混淆:
if ($product_id ='10351')使用了赋值运算符=,应该用相等比较==或全等比较===,否则会强制把product_id设为10351,导致条件永远为真。 - 循环逻辑错误:foreach循环中每次都会覆盖
$product_id,最终只会判断订单里最后一个商品的ID,只要订单包含目标商品就应该触发,而不是只看最后一个。 - 语法错误:
$coupon->set_email_restrictions($bemail)末尾缺少分号,会导致PHP语法报错。 - 参数类型错误:
set_email_restrictions()要求传入数组类型的邮箱列表,直接传单个字符串会导致功能失效。 - 未挂载钩子:函数没有绑定到WooCommerce的合适动作钩子(比如订单完成、感谢页加载),无法自动触发执行。
- 优惠券代码重复风险:直接用
$bname . '1990'生成优惠券码,同名用户会重复,导致创建失败。 - 输出不当:使用
echo 'done'可能会干扰WooCommerce的页面输出,应该用系统通知替代。
修正后的代码:
function coupon_code_akki($order_id){ // 获取订单对象 $order = wc_get_order($order_id); if (!$order) return; $target_product_id = '10351'; $has_target_product = false; // 遍历订单商品,检查是否包含目标商品 foreach ($order->get_items() as $item) { if ($item->get_product_id() == $target_product_id) { $has_target_product = true; break; // 找到目标商品就停止遍历 } } // 确认订单包含目标商品才执行优惠券创建 if ($has_target_product) { $bname = $order->get_billing_first_name(); $bemail = $order->get_billing_email(); // 生成唯一优惠券码(避免重复) $coupon_code = sanitize_title($bname . '-' . time() . '-1990'); // 创建优惠券对象 $coupon = new WC_Coupon(); $coupon->set_code($coupon_code); $coupon->set_amount(1990); // 邮箱限制传入数组 $coupon->set_email_restrictions(array($bemail)); // 可选:设置优惠券类型(固定金额) $coupon->set_discount_type('fixed_cart'); // 可选:设置有效期,比如30天有效 $coupon->set_date_expires(date('Y-m-d H:i:s', strtotime('+30 days'))); // 保存优惠券 $coupon->save(); // 给用户添加订单通知 $order->add_order_note('已为您生成专属优惠券:' . $coupon_code); wc_add_notice('感谢您的购买,专属优惠券已发送至您的邮箱!', 'success'); } } // 绑定到订单完成钩子,确保订单支付完成后触发 add_action('woocommerce_order_status_completed', 'coupon_code_akki');
内容的提问来源于stack exchange,提问作者jogin shar
相关产品推荐
相关产品推荐

