How to get order tax details and rates in WooCommerce?

拜拜、爱过 提交于 2021-01-29 04:08:11

问题


I'm trying to get the tax percentage for a custom variable in a plugin from an order. Of course I could request a lot of data via $order-> get_ ..., but I cannot find a method to get the tax percentage (like for example '21' -> 21%).

Anyone have an idea to make this simple?


回答1:


You will have to get order tax item(s) which will give you an array of WC_Order_Item_Tax Objects which protected properties are accessible using WC_Order_Item_Tax available methods like:

// Get the the WC_Order Object from an order ID (optional)
$order = wc_get_order( $order_id );

foreach($order->get_items('tax') as $item_id => $item ) {
    $tax_rate_id    = $item->get_rate_id(); // Tax rate ID
    $tax_rate_code  = $item->get_rate_code(); // Tax code
    $tax_label      = $item->get_label(); // Tax label name
    $tax_name       = $item->get_name(); // Tax name
    $tax_total      = $item->get_tax_total(); // Tax Total
    $tax_ship_total = $item->get_shipping_tax_total(); // Tax shipping total
    $tax_compound   = $item->get_compound(); // Tax compound
    $tax_percent    = WC_Tax::get_rate_percent( $tax_rate_id ); // Tax percentage
    $tax_rate       = str_replace('%', '', $tax_percent); // Tax rate


    echo '<p>Rate id: '. $tax_rate_id . '<br>'; // Tax rate ID
    echo 'Rate code: '. $tax_rate_code . '<br>'; // Tax code
    echo 'Tax label: '. $tax_label . '<br>'; // Tax label name
    echo 'Tax name: '. $tax_name . '<br>'; // Tax name
    echo 'Tax Total: '. $tax_total . '<br>'; // Tax Total
    echo 'Tax shipping total: '. $tax_ship_total . '<br>'; // Tax shipping total
    echo 'Tax compound: '. $tax_compound . '<br>'; // Tax shipping total
    echo 'Tax percentage: '. $tax_percent . '<br>'; // Tax shipping total
    echo 'Tax rate: '. $tax_rate . '</p>'; // Tax percentage
}

Tested and works

You can also use some WC_Tax available methods like in the code

Note that you can have many 'tax" items with different tax rates in an order. Shipping can have its own tax rate too. Same thing for fees, as you can set a tax class. Also remember that taxes rates are based on customer location.


Finally you can also use some WC_Abstract_Order methods to get taxes amounts details like:

// Get the the WC_Order Object from an order ID (optional)
$order = wc_get_order( $order_id );

$discount_tax         = $order->get_discount_tax();
$shipping_tax_total   = $order->get_shipping_tax();
$order_total_tax      = $order->get_total_tax();
$cart_total_tax       = $order->get_cart_tax();
$formatted_tax_totals = $order->get_tax_totals();


来源:https://stackoverflow.com/questions/62281434/how-to-get-order-tax-details-and-rates-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!