Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the cart totals non formatted values as float numbers in WooCommerce

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();
like image 609
Kostiantyn Petlia Avatar asked Oct 21 '25 04:10

Kostiantyn Petlia


1 Answers

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

like image 119
LoicTheAztec Avatar answered Oct 23 '25 17:10

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!