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

订单完成后自动创建WooCommerce促销码问题求助

WooCommerce礼品券自动生成促销码问题排查与修复

原代码存在的核心问题

  • 缺失关键函数:代码中调用的generate_unique_voucher_code()未定义,执行到此处会直接报错中断后续流程
  • 优惠券创建方式不规范:直接用wp_insert_post操作数据库创建优惠券,未使用WooCommerce官方的WC_Coupon类,容易遗漏必要的元数据或触发相关钩子
  • 过期日期格式错误:WooCommerce优惠券的expiry_date要求是YYYY-MM-DD格式,原代码用时间戳存储无法被系统识别
  • 钩子选择可能不合适:woocommerce_order_status_completed需要订单状态变为「已完成」才触发,部分支付网关支付后订单会先处于「处理中」状态,导致代码不执行
  • 类型匹配问题:$product_id === $specific_product_id用全等比较,若商品ID类型不一致(比如一个是整数一个是字符串)会导致判断失败

修复后的完整代码

// 改用支付完成时触发的钩子,更精准匹配礼品券场景
add_action('woocommerce_payment_complete', 'custom_promo_code_creation', 10, 1);
function custom_promo_code_creation($order_id) {
    $order = wc_get_order($order_id);
    if (!$order) return; // 确保订单对象有效

    $specific_product_id = 2081;
    $gift_card_amount = 0;

    foreach ($order->get_items() as $item) {
        // 用宽松比较避免类型问题,定位礼品券商品
        if ($item->get_product_id() == $specific_product_id) {
            $gift_card_amount = $item->get_total();
            break;
        }
    }

    if ($gift_card_amount <= 0) return; // 金额无效则终止流程

    // 实现唯一优惠券码生成逻辑
    function generate_unique_voucher_code($length = 10) {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $code = '';
        do {
            $code = substr(str_shuffle($chars), 0, $length);
            // 校验优惠券码是否已存在
            $exists = get_page_by_title($code, OBJECT, 'shop_coupon');
        } while ($exists);
        return $code;
    }

    // 使用WooCommerce官方类创建优惠券,符合系统规范
    $coupon = new WC_Coupon();
    $coupon_code = generate_unique_voucher_code();
    $coupon->set_code($coupon_code);
    $coupon->set_discount_type('fixed_cart');
    $coupon->set_amount($gift_card_amount);
    $coupon->set_individual_use(true);
    $coupon->set_usage_limit(1);
    // 转换为WooCommerce要求的过期日期格式
    $expiry_date = date('Y-m-d', strtotime('+3 months'));
    $coupon->set_date_expires($expiry_date);
    $coupon->save();

    // 可选:将优惠券信息添加到订单备注,方便用户和商家查看
    $order->add_order_note(sprintf('已生成礼品券优惠券:%s,金额:%s元,有效期至:%s', $coupon_code, $gift_card_amount, $expiry_date));
    $order->save();
}

额外调试建议

如果修复后仍不生效,可添加日志排查执行流程:

// 在关键步骤插入日志,查看代码执行情况
error_log('礼品券优惠券生成触发,订单ID:' . $order_id);
error_log('识别到的礼品券金额:' . $gift_card_amount);
error_log('生成的优惠券码:' . $coupon_code);

日志文件位于wp-content/debug.log,需先在wp-config.php中开启调试:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 09:07:30