I want to export only the coupon totals from items with reduced tax rate (the totals you can see in the image below).
With the totals of these items I do the same. A great answer helped me to export only the totals of order items with reduced tax rate. For that I'm using the following code:
// gets the total of the order items by tax class
function get_total_order_items_by_tax_class( $order_id, $tax_class = 'reduced-rate' ) {
$order = wc_get_order( $order_id );
// initializes the total of the order items
$total = 0;
foreach( $order->get_items() as $item_id => $order_item ) {
// if the product tax class is equal to "$tax_class"
if ( $tax_class == $order_item['tax_class'] ) {
// sum the total
$total += $order_item['total'];
}
}
return $total;
}
I tried something similar and added the line (found here):
$order->get_discount_total();
to the snippet. But this exports the whole discount for every item of every tax class.
I also tried the following code from this answer:
foreach( $order->get_coupon_codes() as $coupon_code ) {
// Get the WC_Coupon object
$coupon = new WC_Coupon($coupon_code);
$discount_type = $coupon->get_discount_type(); // Get coupon discount type
$coupon_amount = $coupon->get_amount(); // Get coupon amount
}
But it's also the discount for the whole order.
Is there any way to get the discount totals only for items with reduced tax rates? I believe that there must be a way because the order shows these totals below every item. But I couldn't find a way to get these discounts.
I saw that $order
only contains the coupon total and the coupon tax. Not per line item. And it seems that $order_item
doesn't contain any discounts. Only something line WC_Coupon_Data_Store_CPT
.
Try the following to get order items discount amount by tax class:
// Get order items discount amount excl. taxes by tax class
function get_order_items_discount_total_by_tax_class( $order_id, $tax_class = 'reduced-rate' ) {
$order = wc_get_order( $order_id );
$discount = 0; // Initializing;
foreach( $order->get_items() as $item ) {
// if the product tax class is equal to "$tax_class"
if ( $tax_class == $item['tax_class'] ) {
$discount += $item->get_subtotal() - $item->get_total(); // Excluding taxes
}
}
return $discount;
}
It should work.
Related: Get Order items and WC_Order_Item_Product in WooCommerce 3