I'm trying to get all product tax rates from order items in WooCommerce orders.
Based on Get tax rate used in an order for one product and for shipping in WooCommerce answer code, I built a loop for order items:
foreach ($order->get_items() as $item_key => $item_value) {
$item_data = $item_value->get_data();
$product_id = $item_value['product_id'];
$product = wc_get_product($product_id);
$wc_product = $item_value->get_product(); // prodotto in WooCommerce
$sku = '';
if(!empty($wc_product))
$sku = $wc_product->get_sku();
$product_type = $item_value->get_type();
if ($item_data['variation_id'] !== 0) {
$variation = $item_data['variation_id'];
$var_data = new \WC_Product_Variation($variation);
$var_attr = implode(', ', $var_data->get_variation_attributes());
}
$tax_rates = \WC_Tax::get_rates($item_data['tax_class']);
if (!empty($tax_rates)) {
$tax_rate = reset($tax_rates);
}
$rateId = key($tax_rates);
$rate = \WC_Tax::get_rate_percent_value($rateId);
$rateDescription = \WC_Tax::get_rate_label($rateId);
/* in questo array ho tutti i dati che mi servono,
* sotto la chiave data raggruppo item_data
*/
$order_items_data[] = array(
'product_id' => $product_id,
'sku' => $sku,
'product_type' => $product_type,
'variation_attr' => $var_attr,
'price' => $fixnum($item_data['subtotal'] / $item_data['quantity'], 6),
'discount' => $item_data['subtotal'] - $item_data['total'],
'tax_rate' => $rate,
'tax_description' => $rateDescription,
'tax_id' => $rateId,
'data' => $item_data
);
}
This code does its work correctly when the order is added on site frontend.
When I add a new order by admin I get an empty $tax_rates
array, that's my issue. Any suggestions?