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();
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()->cartreplace totallyglobal $woocommerce;with$woocommerce->cart, so no need to use outdatedglobal $woocommerce;with it…
Related official documentation: WC_Cart class api, methods and properties
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With