Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get woocommerce carts total amount

I am trying to apply a discount to a carts total price, but I can only do it to the item base price and not the over all price. I Googled and came across this post in the wordpress stackoverflow:

$amount = floatval( preg_replace( '#[^\d.]#', '', $woocommerce->cart->get_cart_total() ) ); 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.

I tried adding:

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

and changing

$discount = round( (($discounting_amount / 100 ) *  $this->amount)*-1, WC()->cart->dp); 

to

$discount = round( (($discounting_amount / 100 ) *  $amount2)*-1, WC()->cart->dp); 

But I get the following error:

Fatal error: Call to a member function get_cart_total() on a non-object in... 
like image 788
Howli Avatar asked Mar 07 '14 12:03

Howli


People also ask

What is cart total?

the sub total refers to total price of all products in the cart and the cart total is the amount after taxes and shipping.

How do I get cart item data in WooCommerce?

Use the WC()->cart method to get woocommerce cart item data. Cart page use this method to load all the values on the cart page e.g. woocommerce get cart item totals, subtotal, get cart items to count, get items price, etc.


2 Answers

Try this:

WC()->cart->cart_contents_total 

The function get_cart_total uses wc_price function thas converts cart_contents_total to currency.

like image 189
zennin Avatar answered Sep 23 '22 08:09

zennin


You need to call the global variable to ensure that it gets the correct values.

If you add

 global $woocommerce; 

just before

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

that should solve your problem.

like image 28
Ronan Avatar answered Sep 22 '22 08:09

Ronan