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

如何获取WooCommerce订单各商品的税率百分比(适配计税设置)

在WooCommerce订单中获取商品对应税率百分比(适配三种计税依据)

核心解决思路

WooCommerce创建订单时,会将商品实际适用的税率信息关联到订单项中,也可通过订单的计税上下文(即你设置的「计税依据」)重新计算准确税率,完全避免反推带来的精度问题。

你之前代码的问题分析

  • 代码1:直接调用WC_Tax::get_rates()仅读取商品税类对应的默认税率,未结合订单实际地址,无法匹配客户所在地的税率
  • 代码2:遍历订单的tax类型项得到的是汇总后的税项,无法直接对应到单个商品
  • 代码3:get_rates_from_location()的参数存在空值未过滤的情况,导致税率匹配失败

解决方案

方案1:直接从订单项元数据读取已保存的税率

下单时WooCommerce会把商品适用的税率百分比保存到订单项元数据中,直接读取即可获得最准确的结果:

$order = wc_get_order($orderId);

foreach ($order->get_items() as $item) {
    // 获取订单项的实际税率百分比
    $tax_rate_percent = $item->get_meta('_line_tax_rate');
    
    // 处理复合税率的情况(取第一个适用税率)
    if (is_array($tax_rate_percent)) {
        $tax_rate_percent = reset($tax_rate_percent);
    }
    
    // 输出结果
    if (!empty($tax_rate_percent)) {
        echo sprintf('%s 的税率:%.2f%%', $item->get_name(), $tax_rate_percent) . PHP_EOL;
    } else {
        echo $item->get_name() . ' 无税' . PHP_EOL;
    }
}

方案2:根据「计税依据」设置重新计算税率

如果订单项元数据丢失,或需要主动适配计税规则,可根据订单对应地址重新计算:

$order = wc_get_order($orderId);
// 获取WooCommerce后台的计税依据设置
$tax_based_on = get_option('woocommerce_tax_based_on');

foreach ($order->get_items() as $item) {
    $product = $item->get_product();
    if (!$product) continue;
    
    // 根据计税依据选择对应地址
    switch ($tax_based_on) {
        case 'base':
            // 店铺基础地址
            $location = wc_get_base_location();
            break;
        case 'billing':
            // 客户账单地址
            $location = [
                'country' => $order->get_billing_country(),
                'state'   => $order->get_billing_state(),
                'postcode'=> $order->get_billing_postcode(),
                'city'    => $order->get_billing_city(),
            ];
            break;
        case 'shipping':
            // 客户收货地址
            $location = [
                'country' => $order->get_shipping_country(),
                'state'   => $order->get_shipping_state(),
                'postcode'=> $order->get_shipping_postcode(),
                'city'    => $order->get_shipping_city(),
            ];
            break;
        default:
            $location = wc_get_base_location();
            break;
    }
    
    // 过滤空值,避免税率匹配失败
    $location = array_filter($location);
    
    // 获取对应地址和商品税类的税率
    $tax_rates = WC_Tax::get_rates_from_location($product->get_tax_class(), $location);
    
    if (!empty($tax_rates)) {
        $rate = reset($tax_rates);
        echo sprintf('%s 的税率:%.2f%%', $item->get_name(), $rate['rate']) . PHP_EOL;
    } else {
        echo $item->get_name() . ' 无适用税率' . PHP_EOL;
    }
}

补充说明

  • 优先使用方案1,因为这是订单创建时实际计算的税率,无需二次计算且精度100%
  • 方案2需确保WooCommerce后台的税规则配置正确,否则可能返回空或错误税率
  • 绝对避免反推税率:商品可能存在折扣、优惠等调整项,反推会出现非标准的精度误差,无法满足API接口的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 07:51:08