如何在 WooCommerce 中获取订单税务详细信息和税率?

Thi*_*orn 2 php wordpress orders woocommerce tax

我正在尝试从订单中获取插件中自定义变量的税率。当然,我可以通过 请求大量数据$order-> get_ ...,但我找不到获取税率的方法(例如“21”-> 21%)。

有人有想法让这变得简单吗?

Loi*_*tec 13

您必须获得订单税项,这将为您提供一组对象,可以使用以下可用方法WC_Order_Item_Tax访问受保护的属性:WC_Order_Item_Tax

// 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
}
Run Code Online (Sandbox Code Playgroud)

经过测试并有效

您还可以使用一些WC_Tax可用的方法,如代码中所示

请注意,您的订单中可以有许多具有不同税率的“税”商品。运输也可以有自己的税率。费用也是如此,因为您可以设置税级。另请记住,税率取决于客户所在位置。


最后,您还可以使用一些WC_Abstract_Order方法来获取税额详细信息,例如:

// 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();
Run Code Online (Sandbox Code Playgroud)