8

Is it possible to get the cart total price without any markup. So without the € symbol? Right now I'm getting the amount with:

$totalamount = $woocommerce->cart->get_cart_total();  

this will give €16.50

I tried this also:

$totalamount = number_format($woocommerce->cart->get_cart_total(), 2, '.', '');

But this always gives 0.00

Is there a woocommerce get function that will give a number format of the total cart price? Thanks!

2 Answers 2

9

Update 2020

Answer

See flytech's answer for a solution using the native WooCommerce API.

Note / Caveat

If you're going to do proper arithmetic with monetary values, always use signed integers (!) representing the smallest denomination of a given currency (Cent, Penny, Paisa, Dirham, e.g.).
Only convert back to decimal fractions in the presentation layer of your application after all calculations are done.

This holds true regardless of language or framework.

Original answer

I don't know woocommerce at all and hence there might be a native way as well, but anyhow, this

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

should do.

The preg_replace eliminates everything but decimal characters and colons.

Should you care to do math with it, the floatval converts the value from a string to a numeric one.

3
  • Thanks, I already worked it out with some kind of solution indeed.
    – Trekdrop
    Sep 24, 2013 at 11:59
  • For some countries you have to consider the comma too, try this '#[^\d.,]#'
    – j.c
    May 19, 2017 at 8:52
  • 1
    I'd warn you about this issue: if you set dots and commas in woocommerce general settings you can have unwanted results with this method. Example: amount = 1.239,90$ can be read as 1,239$. I'd suggest this solution
    – j.c
    Jul 28, 2017 at 19:05
24

That is what you want:

Working with global variable:

global $woocommerce;  
$woocommerce->cart->total;

Working with function:

WC()->cart->total;
7
  • 4
    Please add an explanation to your answer: why could that solve the problem?
    – fuxia
    Feb 11, 2014 at 9:09
  • yes! this works; it strips the currency symbol
    – numediaweb
    Apr 5, 2014 at 17:14
  • 1
    If I use this in the cart it only works properly when the cart is visited, not if someone uses update cart ... anyone know why? Mar 26, 2015 at 21:28
  • This should be the correct answer. Depending on context (e.g. mine), WC()->cart->total also works nicely.
    – rrrhys
    Sep 22, 2015 at 22:13
  • on any page you declare $woocommerce as global variable and the you can access most of the stuff that you need. Nov 16, 2015 at 21:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.