Categories
Uncategorized

Store And Restore WooCommerce Cart Data

I was working on a problem where one of my ideas was to store the current cart data away temporarily, use the cart for my requirement, empty the cart and then finally restore the cart data which we stored away in temporary variable before.

To do this, first get the cart content as follows:

$cart_contents = WC()->cart->get_cart_contents();

Then empty the cart:

if ( count( WC()->cart->get_cart() ) > 0 ) {
	WC()->cart->empty_cart();
}

We could combine all the code above into one as follows:

if ( count( WC()->cart->get_cart() ) > 0 ) {
	$cart_contents = WC()->cart->get_cart_contents(); // Backup the cart content to restore it later.
	WC()->cart->empty_cart();
}

We could now use the cart for whatever we need to get done. Then finally restore our backed up cart as follows:

// Restore the backed up cart content.
foreach ( $cart_contents as $key => $values ) {
	$id       = $values['product_id'];
	$quantity = $values['quantity'];
	WC()->cart->add_to_cart( $id, $quantity );
}

That pretty much covers everything about storing and restoring the WooCommerce cart data. If you have any questions, let me know in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *