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

编程创建WooCommerce订单时,赠品零价导致订单总额计算错误如何解决?

WooCommerce编程创建含赠品订单时金额计算错误的解决方案

你遇到的问题核心是:添加赠品后手动修改订单项为0价,调用calculate_totals时系统会重新根据产品原始价格计算总额,导致手动设置的0价被覆盖,最终订单总额计算错误。

解决方法

核心思路是在添加赠品订单项时直接传入0价参数,而非先添加再修改,这样calculate_totals会保留自定义价格设置,不会被产品原始价格覆盖。

修改后的完整代码如下:

$order = wc_create_order(array('customer_id' => $currentUserId));

// 添加付费产品
foreach($cartProductInfo as $productIn) {
    $order->add_product( wc_get_product($productIn['id']), $productIn['qty'] );
}

// 添加0价赠品
foreach($data['gift'] as $productIn) {      
    $product = wc_get_product($productIn['productId']);
    // 添加产品时直接传入自定义价格属性
    $order->add_product(
        $product,
        1,
        array(
            'subtotal'     => 0,
            'total'        => 0,
            'subtotal_tax' => 0,
            'total_tax'    => 0,
        )
    );
    
    // 获取刚添加的订单项,添加赠品标识元数据
    $order_items = $order->get_items();
    $last_item = end($order_items);
    if ($last_item) {
        $last_item->add_meta_data('is_free_gift', true);
        $last_item->add_meta_data('offer_type', $productIn['offer_type']);
        $last_item->save();
    }
} 

// 计算并更新订单总额
$order->calculate_totals();    
$order->save();

关键说明

  • 替换旧函数:用新版WooCommerce推荐的wc_get_product替代get_product,提升版本兼容性。
  • 自定义订单项参数:add_product的第三个参数支持传入订单项属性数组,直接设置subtotal、total等为0,确保添加时就写入正确价格。
  • 避免后修改覆盖:calculate_totals会重新计算订单项价格,如果先添加再手动修改,该方法会用产品原始价格覆盖自定义值,因此必须在添加时就传入正确价格。
  • 简化元数据添加:通过获取订单最后一个订单项来添加赠品标识,确保对应到刚添加的赠品。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:26:14