WooCommerce:仅针对特定税种的商品获取折扣总额

问题描述

我只想导出税率降低的商品的优惠券总额(您可以在下图中看到的总额)。

对于这些项目的总数,我也这样做。 A great answer helped me 仅导出税率降低的订单商品的总数。为此,我使用以下代码

// 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;
}

我尝试了类似的方法添加了行 (found here):

$order->get_discount_total();

到片段。但这会导出每个税种的每个项目的全部折扣。

我还尝试了 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
}

但这也是整个订单的折扣。

有没有办法只获得税率降低的商品的折扣总额? 我相信一定有办法,因为订单会在每个项目下方显示这些总计。 但我找不到获得这些折扣的方法

我看到 $order 只包含优惠券总额和优惠券税。不是每个订单项。并且似乎 $order_item 不包含任何折扣。只有某行WC_Coupon_Data_Store_CPT

enter image description here

解决方法

尝试以下操作以获取按税种分类的订单商品折扣金额:

// 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;
}

它应该可以工作。

相关: Get Order items and WC_Order_Item_Product in WooCommerce 3