Dylan de St Pern
Dylan de St Pern

Reputation: 469

Woocommerce cart mockup for retrieving cart total

I need to calculate the total amount that a cart will cost with multiple products and coupons added. I need to get this total without changing the global WC()->cart. So my thoughts were to create a temporary cart, add all the items and coupons and then return WC_Cart:get_total();

Here's my code:

//5438 is my product (simple subscription, $55 with a $50 signup fee)
//product_schedule_discount is the coupon code that removes 100% of the signup fee

$tmpCart = new WC_Cart();
$tmpCart->add_to_cart( 5438, '1', '0', array(), array() );
$tmpCart->apply_coupon('product_schedule_discount');
$tmpCart->calculate_totals( );
$cartTotal = $tmpCart->get_total();
$tmpCart->remove_coupon('product_schedule_discount');
return $cartTotal;

This method works when I get the total, without adding a coupon. But when I want to add a coupon, it seems to apply the coupon to the users session, because when I go to the cart page (totally separate from where I'm using the above code, I see a message 'Coupon loaded successfully.'. And when I refresh the page it's gone. The second problem is that it does not return the new total (with coupons applied) until I request it to run again.

Why is it showing my the message on my cart page? Should it not apply to the cart that I tell it to? In this case, my $tmpCart?

I need to get the total of the cart because I'm writing my own module which allows my customers to create mockup carts.

Here's reference to the methods I'm using:

WC_Cart::get_totals

WC_Cart::apply_coupon

Upvotes: 1

Views: 295

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253868

You can't have 2 Cart objects as the same time. When you create a new cart object, it replaces the existing one (if there is one). Cart object is a live frontend object, so it can't work this way.

For the message: It's is normal as apply_coupon() method generate a notice that is stored in WC_Session and then displayed immediately displayed after loading a page (or with ajax).

For the total issue: I don't have the issue you relate. I get the correct total which is the cart total with the coupon discount.

Upvotes: 1

Related Questions