简体   繁体   中英

Get cart total as a float number in WooCommerce 3+

In WooCommerce,

<?php echo WC()->cart->get_cart_total(); ?>

gives me €1,750.00

How can I get this as a floating number so I can multiply it?

I tried every solution in these two SO questions:

Unable to get cart total in woocommerce

woocommerce - Get Cart Total as number

All outdated and not working. Does anyone know how to do this?

You can refer to WooCommerce WC_Cart official documentation

This should work:

WC()->cart->get_total("anything_else_than_'view'");

Explanations:

Thanks to btomw that pointed out that an argument need to be defined in WC_Cart get_total() method. If you call this method without defining an argument (that should be anything else than 'view' string) , the output is going to be the formatted total price, as 'view' default argument will be used by this method. So if you want to get a float value (non formatted) , set as argument anything else that is not 'view', even an empty string like '' . As you can see on this method documentation , it's for backwards compatibility since WooCommerce 3.2.

As an alternative to the answer of Sar Putnik , With WC_Cart object you can directly access properties like total , which gives a non formatted number:

$total = WC()->cart->total;

// Testing output
var_dump($total);

It will give the same output if using $total = WC()->cart->get_total("");

Note that, since WooCommerce 3, on other WooCommerce instance objects you can't access properties directly … But some few classes as WC_Cart still allow that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM