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

自定义WooCommerce支付页优惠券功能无法识别Smart Coupons礼品卡金额

解决WooCommerce Smart Coupons礼品卡自定义应用后抵扣金额为0的问题

问题根源

WooCommerce Smart Coupons的礼品卡并非普通优惠券,它依赖插件自身的专属逻辑处理金额计算、余额扣除等操作。直接使用WC_Coupon实例化并调用apply_coupon(),只会完成基础的优惠券关联,不会触发Smart Coupons的核心计算流程,导致订单抵扣金额未被正确更新。

解决方案

1. 使用Smart Coupons专属函数应用礼品卡

Smart Coupons内置了专门用于订单应用优惠券/礼品卡的函数,优先用这个替代原生apply_coupon():

$coupon_code = sanitize_text_field($_POST['coupon_code']);

// 检查是否为Smart Coupons礼品卡
if (function_exists('wc_sc_is_gift_card')) {
    if (!wc_sc_is_gift_card($coupon_code)) {
        // 非礼品卡走原生逻辑
        $coupon = new WC_Coupon($coupon_code);
        if (!$coupon->get_id()) {
            wp_send_json_error('Invalid coupon.');
        }
        $order->apply_coupon($coupon);
    } else {
        // 礼品卡调用插件专属函数
        $applied = wc_sc_apply_coupon_to_order($coupon_code, $order->get_id());
        if (is_wp_error($applied)) {
            wp_send_json_error($applied->get_error_message());
        }
    }
} else {
    // 插件未激活时走原生逻辑
    $coupon = new WC_Coupon($coupon_code);
    if (!$coupon->get_id()) {
        wp_send_json_error('Invalid coupon.');
    }
    $order->apply_coupon($coupon);
}

// 强制触发包含Smart Coupons逻辑的总额计算
do_action('woocommerce_after_calculate_totals', $order);
$order->calculate_totals();
$order->save();

2. 手动触发礼品卡计算逻辑

如果上述函数不可用,可在原生方法调用后手动触发插件的计算钩子:

$coupon_code = sanitize_text_field($_POST['coupon_code']);

$coupon = new WC_Coupon($coupon_code);
    
if (!$coupon->get_id()) {
    wp_send_json_error('Invalid coupon.');
}

$order->apply_coupon($coupon);

// 触发Smart Coupons礼品卡金额计算
if (class_exists('WC_SC_Gift_Cards')) {
    WC_SC_Gift_Cards::calculate_gift_card_discount($order);
}

$order->calculate_totals();
$order->save();

3. 补全订单抵扣金额元数据

若仍有问题,可手动检查并更新订单元数据:

// 读取Smart Coupons写入的礼品卡抵扣金额
$gift_card_discount = $order->get_meta('_wc_sc_gift_card_discount', true);
if (!empty($gift_card_discount)) {
    // 合并到订单总抵扣金额
    $order->set_discount_total($order->get_discount_total() + $gift_card_discount);
    $order->save();
}

调试建议

  • 开启WooCommerce调试模式,查看错误日志中是否有Smart Coupons相关警告
  • 对比后台手动应用礼品卡后的订单元数据,确认自定义代码是否遗漏关键字段更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 07:52:45