12
votes

I want to get total price of cart in my woocommerce plugin.

I want to get it as a float number like so: 21.00 but I don't know how to get it. My code outputs weird results, this is my exact code:

$total         = $woocommerce->cart->get_total();
$total_a       = WC()->cart->get_total();
$total1        = $woocommerce->cart->get_total_ex_tax();
$total1_a      = WC()->cart->get_total_ex_tax();
$total2        = $woocommerce->cart->get_cart_total();
$total2_a      = WC()->cart->get_cart_total();

outputs:

0,00 €
0,00 €
0,00 €
0,00 €
21,00 €
21,00 €

and if I convert from string to float the result is of course 0.00.

Any help how to get cart total in the form of float number ?

9
Look in the cart class. get_total() method formats the price using wc_price(). So, as @José has pointed out you just need to access the public property. - helgatheviking

9 Answers

12
votes

I have code like this and working perfect:

if ( ! WC()->cart->prices_include_tax ) {
    $amount = WC()->cart->cart_contents_total;
} else {
    $amount = WC()->cart->cart_contents_total + WC()->cart->tax_total;
}

good luck !

10
votes

Just access the total property directly, it's public:

global $woocommerce;
echo $woocommerce->cart->total;
4
votes
global $woocommerce;
$amount = $woocommerce->cart->cart_contents_total+$woocommerce->cart->tax_total;

You can also convert $amount in float value as per your requirement.

2
votes
global $woocommerce;
$woocommerce->cart->cart_contents_total (Cart total)
$woocommerce->cart->tax_total (tax total)
$woocommerce->cart->shipping_total (shipping total)
2
votes

Try this WC()->cart->cart_contents_total

1
votes

In 2020 with Woocommerce 4+

$total_cart = WC()->cart->get_displayed_subtotal(); // without taxs and shipping fees
echo $total_cart; // ex: 0.00
1
votes

The best approach is to use get_total() while passing in a context other than the default of 'view'. When the context is view, the price will be formatted for display. When set to anything else, it'll pass back the raw value.

Example:

WC()->cart->get_total( 'raw' );

It's also worth noting that $woocommerce (providing you've accessed the global first of course) is exactly the same as WC(). I'd recommend preferring WC() whereever possible.

0
votes

There are methods for it, you don't need to get them from a property.

Use: WC()->cart->get_cart_contents_total()

Instead of: WC()->cart->cart_contents_total


And use: WC()->cart->get_taxes_total()

Instead of: WC()->cart->tax_total

0
votes

Woocommerce 4.8 WC()->cart->total works fine, although it worries me a little getting this value without a help of a getter but it seems to be the easiest method right now.