4

How can I get the cart total/total_ex_tax as float number?

I looked for, but all answers are like:

a) Ugly usage reg_exp (For example, what if we will be to use ',' instead '.'?):

global $woocommerce;
$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) );

b) Direct access to class properties (which can be to change in future; and not the OOP method). It works, but it's a wrong way:

global $woocommerce;
echo $woocommerce->subtotal;
echo $woocommerce->subtotal_ex_tax;
echo $woocommerce->total;
echo $woocommerce->total_ex_tax;
echo $woocommerce->cart_contents_total;

I want to get normal API something like this:

$wc = WC();
echo $wc->cart->get_total_as_number();
echo $wc->cart->get_total_ex_tax_as_number();
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • [woocommerce - Get Cart Total as number](https://stackoverflow.com/questions/30063173/woocommerce-get-cart-total-as-number) might help – Masivuye Cokile Dec 15 '17 at 11:49

1 Answers1

3

Using WC()->cart (the WC_Cart class object) you can use methods or access properties listed on the following WC_Cart class documentation Api.

So with WC()->cart you can access the properties directly and get non formatted values using:

echo WC()->cart->subtotal;
echo WC()->cart->subtotal_ex_tax;
echo WC()->cart->total;
echo WC()->cart->total_ex_tax;
echo WC()->cart->cart_contents_total;

You will get float numbers for all. Remember that WC()->cart is a live object.

WC()->cart replace totally global $woocommerce; with $woocommerce->cart, so no need to use outdated global $woocommerce; with it…


Related official documentation: WC_Cart class api, methods and properties

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399