获取订单商品税率

问题描述 投票:0回答:1

在订单上,我想获取每件商品的税率(例如:20%),但 WooCommerce 仅返回计算值。

我需要它来处理 WooCommerce 选项“计算税金”(对于每种情况:“商店基本地址”、“客户账单地址”和“客户送货地址”)

我尝试了不同的代码,但没有一个返回良好的结果:

1) 退货百分比并非基于客户位置

$order = wc_get_order($orderId);

foreach ($order->get_items() as $item) {
    $product = $item->get_product();

    $tax = new WC_Tax();
    $taxes = $tax->get_rates($product->get_tax_class());
    $rates = array_shift($taxes);

    var_dump($rates);
    // array(4) { ["rate"]=> float(20) ["label"]=> string(3) "TVA" ["shipping"]=> string(3) "yes" ["compound"]=> string(2) "no" } 
}

2)每个产品不退税

$order = wc_get_order($orderId);

foreach ($order->get_items('tax') as $tax_item) {
    var_dump($tax_item->get_data());
    // array(11) { ["id"]=> int(457) ["order_id"]=> int(143) ["name"]=> string(0) "" ["rate_code"]=> string(8) "BE-TVA-1" ["rate_id"]=> int(4) ["label"]=> string(3) "TVA" ["compound"]=> bool(false) ["tax_total"]=> string(2) "66" ["shipping_tax_total"]=> int(0) ["rate_percent"]=> float(75) ["meta_data"]=> array(0) { } } 
}

3)返回空数组

$order = wc_get_order($orderId);

foreach ($order->get_items() as $item_id => $item) {
    $product = $item->get_product();
    $taxes = WC_Tax::get_rates_from_location($product->get_tax_class(), [
        'country' => $order->get_billing_country(),
        'state' => $order->get_billing_state(),
        'postcode' => $order->get_billing_postcode(),
        'city' => $order->get_billing_city(),
    ]);

    var_dump($taxes);
    // array(0) { }
}

我也尝试过计算来获取百分比,但有时会得到不一致的值(例如:5,51111%)并且无法使用它们,因为它将被发送到需要有效百分比值的 API。

wordpress woocommerce
1个回答
0
投票

您可以尝试以下方法获取每个订单项目的税率

$order     = wc_get_order($order_id); // Get WC_Order object from order ID
$tax_rates = array(); // Initializing

// Loop through order tax items
foreach ( $order->get_items('tax') as $item ) {
    $tax_rates[$item->get_rate_id()] = $item->get_rate_percent();
}

// Loop through order line items
foreach ( $order->get_items() as $item ) {
    $item_taxes   = $item->get_taxes(); // Get item taxes array
    $tax_rate_id  = current( array_keys($item_taxes['subtotal']) );

    $tax_percent  = $tax_rates[$tax_rate_id]; // The tax percentage for the current item
    echo '<pre>Tax percentage: '. print_r($tax_percent, true ) . '%</pre>';
    
    $tax_subtotal = $item_taxes['subtotal'][$tax_rate_id]; // item tax subtotal (non rounded)
    $tax_total    = $item_taxes['total'][$tax_rate_id]; // item tax total (coupon discounted, non rounded)
    echo '<pre>Tax subtotal: '. print_r($tax_subtotal, true ) . '</pre>';
    echo '<pre>Tax total (discounted): '. print_r($tax_total, true ) . '</pre>';
}
© www.soinside.com 2019 - 2024. All rights reserved.