1
votes

Based of Calculate fee from cart totals (subtotal + shipping) without adding it to order total value in Woocommerce

I know how to get cart totals. Fees and discounts are included in the calculation.

// Get cart subtotal & shipping total & fees & discounts
    
$subtotal                = WC()->cart->subtotal;
$shipping_total          = WC()->cart->get_shipping_total();
$fees                    = WC()->cart->get_fee_total();
$discount_excl_tax_total = WC()->cart->get_cart_discount_total();
$discount_tax_total      = WC()->cart->get_cart_discount_tax_total();

$discount_total          = $discount_excl_tax_total + $discount_tax_total;

// Cart Total
$cart_total = $subtotal + $shipping_total + $fees - $discount_total;

I need to get order totals also. I have a problem getting order discounts and fees.

function filter_woocommerce_get_order_item_totals( $order ) {    
    
// Get order subtotal & shipping total & fees & discounts

$order_subtotal              = $order->get_subtotal();
$order_shipping_total        = $order->get_shipping_total();
$order_fees                  = ...
$order_discounts             = ...

// Order Total
$order_total = $order_subtotal + $order_shipping_total + $order_fees - $order_discounts;

Order totals will be displayed on the order-received / thank-you page.

How can I get order fees and discount amounts for order totals calculation?

Below code does not seem to be the right answer:

$order_fees       = $order->get_fees();
$order_discounts  = $order->get_discount_total();
1

1 Answers

0
votes

Contrary to what you might expect, $order->get_fees() will not return a number. This is because the result is an array.

WC_Abstract_Order::get_fees() – Return an array of fees within this order.

So you would get:

$order_id = 2878;

// Get $order object
$order = wc_get_order( $order_id );

// Is a WC_Order
if ( is_a( $order, 'WC_Order' ) ) {
    $order_fees = 0;
    
    // Get fees
    foreach ( $order->get_fees() as $fee_id => $fee ) {
        // Get total
        $order_fees += $fee['line_total'];

        // OR $order_fees += $fee->get_total();
    }
    
    echo $order_fees;
}

Or in your case:

// Get subtotal
$order_subtotal = $order->get_subtotal();

// Get shipping total
$order_shipping_total = $order->get_shipping_total();

// Initialize
$order_fee_total = 0;

// Get fees
foreach ( $order->get_fees() as $fee_id => $fee ) {
    $order_fee_total += $fee->get_total();
}

// Get discount total
$order_discount_total = $order->get_discount_total();

// Order Total
$order_total = $order_subtotal + $order_shipping_total + $order_fee_total - $order_discount_total;