【问题标题】:WooCommerce: Get discount total only for items from a specific tax classWooCommerce:仅获取特定税类商品的折扣总额
【发布时间】:2021-06-01 11:27:57
【问题描述】:

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

对于这些项目的总数,我也会这样做。 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();

到sn-p。但这会导出每个税级的每个项目的全部折扣。

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

【问题讨论】:

    标签: php wordpress woocommerce orders tax


    【解决方案1】:

    尝试以下方法按税级获取订单商品折扣金额:

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

    【讨论】:

    • 太好了,就是这样!
    猜你喜欢
    • 2021-06-01
    • 2019-02-06
    • 2019-06-13
    • 1970-01-01
    • 2017-04-13
    • 2021-05-16
    • 2020-08-18
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多