WC_Abstract_Order::calculate_totals( bool $and_taxes = true )

Calculate totals by looking at the contents of the order. Stores the totals and returns the orders final total.


Description Description


Parameters Parameters

$and_taxes

(Optional) Calc taxes if true.

Default value: true


Top ↑

Return Return

(float) calculated grand total.


Top ↑

Source Source

File: includes/abstracts/abstract-wc-order.php

	public function calculate_totals( $and_taxes = true ) {
		do_action( 'woocommerce_order_before_calculate_totals', $and_taxes, $this );

		$fees_total        = 0;
		$shipping_total    = 0;
		$cart_subtotal_tax = 0;
		$cart_total_tax    = 0;

		$cart_subtotal = $this->get_cart_subtotal_for_order();
		$cart_total    = $this->get_cart_total_for_order();

		// Sum shipping costs.
		foreach ( $this->get_shipping_methods() as $shipping ) {
			$shipping_total += round( $shipping->get_total(), wc_get_price_decimals() );
		}

		$this->set_shipping_total( $shipping_total );

		// Sum fee costs.
		foreach ( $this->get_fees() as $item ) {
			$fee_total = $item->get_total();

			if ( 0 > $fee_total ) {
				$max_discount = round( $cart_total + $fees_total + $shipping_total, wc_get_price_decimals() ) * -1;

				if ( $fee_total < $max_discount && 0 > $max_discount ) {
					$item->set_total( $max_discount );
				}
			}
			$fees_total += $item->get_total();
		}

		// Calculate taxes for items, shipping, discounts. Note; this also triggers save().
		if ( $and_taxes ) {
			$this->calculate_taxes();
		}

		// Sum taxes again so we can work out how much tax was discounted. This uses original values, not those possibly rounded to 2dp.
		foreach ( $this->get_items() as $item ) {
			$taxes = $item->get_taxes();

			foreach ( $taxes['total'] as $tax_rate_id => $tax ) {
				$cart_total_tax += (float) $tax;
			}

			foreach ( $taxes['subtotal'] as $tax_rate_id => $tax ) {
				$cart_subtotal_tax += (float) $tax;
			}
		}

		$this->set_discount_total( round( $cart_subtotal - $cart_total, wc_get_price_decimals() ) );
		$this->set_discount_tax( wc_round_tax_total( $cart_subtotal_tax - $cart_total_tax ) );
		$this->set_total( round( $cart_total + $fees_total + $this->get_shipping_total() + $this->get_cart_tax() + $this->get_shipping_tax(), wc_get_price_decimals() ) );

		do_action( 'woocommerce_order_after_calculate_totals', $and_taxes, $this );

		$this->save();

		return $this->get_total();
	}

Top ↑

Changelog Changelog

Changelog
Version Description
2.2 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.