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

WooCommerce计算订单总金额时如何获取订单费用与折扣金额

WooCommerce 订单费用与折扣金额正确获取及总金额计算方案

问题排查

  • $order->get_fees()返回的是订单费用的对象数组,而非直接的总金额数值,无法直接用于数值计算
  • $order->get_discount_total()仅返回不含税的折扣金额,缺少折扣对应的税额部分,和你之前购物车的计算逻辑不匹配,导致总金额计算错误

正确实现代码

以下代码可直接实现与购物车逻辑对齐的订单总金额计算,并自动展示在order-received/thank-you页面的金额明细中:

function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {    
    // 获取订单基础项金额
    $order_subtotal              = $order->get_subtotal();
    $order_shipping_total        = $order->get_shipping_total();
    
    // 正确获取订单总费用金额,和购物车get_fee_total()逻辑对应
    $order_fees                  = $order->get_total_fees();
    // 若需要兼容旧版WooCommerce,可替换为遍历累加逻辑:
    // $order_fees = 0;
    // foreach ( $order->get_fees() as $fee ) {
    //     $order_fees += $fee->get_total();
    // }
    
    // 正确获取订单总折扣金额(含折扣对应税额,和购物车计算逻辑对齐)
    $discount_excl_tax = $order->get_discount_total();
    $discount_tax = $order->get_discount_tax();
    $order_discounts = $discount_excl_tax + $discount_tax;

    // 计算最终订单总金额
    $order_total = $order_subtotal + $order_shipping_total + $order_fees - $order_discounts;

    // 将自定义计算的总金额添加到订单明细列表
    $total_rows['custom_calculated_total'] = array(
        'label' => '计算总金额:',
        'value' => wc_price( $order_total, array( 'currency' => $order->get_currency() ) )
    );

    return $total_rows;
}
add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 );

逻辑说明

  • 费用获取直接调用get_total_fees()方法即可拿到所有费用的税后总金额,和购物车阶段的计算逻辑完全统一
  • 折扣金额按照你购物车阶段的计算规则,累加不含税折扣和折扣税额两部分,避免前后计算结果不一致
  • 不需要额外修改模板文件,通过过滤器新增的明细行会自动插入到订单金额列表中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:15:03