Abandoned carts are a major pain point for any online store. With WooCommerce, logged-in users benefit from persistent cart sessions, but guest users often lose their cart when they leave the site or close the browser. That’s where this snippet comes in.
This code lets you save the WooCommerce cart to a cookie on page unload and restore it later — even for guests. It enhances user experience and gives you a better shot at recovering lost sales.
How It Works
- When a user is about to leave the site, we fetch the cart content via AJAX and save it as a JSON cookie.
- When they return, the cart is automatically restored from the saved cookie — if applicable.
Code Breakdown
1. Save Cart Contents to Cookie
This script listens for the browser’s beforeunload
event and triggers a fetch request to get current cart data, then stores it in a cookie.
add_action('wp_footer', 'rashed_save_cart_to_cookie');
function rashed_save_cart_to_cookie() {
if ( is_admin() || is_cart() || is_checkout() ) return;
?>
<script type="text/javascript">
window.addEventListener('beforeunload', function () {
if (typeof wc_cart_params === 'undefined') return;
fetch(wc_cart_params.ajax_url + '?action=rashed_get_cart_contents', {
method: 'GET',
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => {
document.cookie = "rashed_saved_cart=" + JSON.stringify(data) + "; path=/; max-age=604800";
});
});
</script>
<?php
}
2. Handle AJAX to Return Cart Contents
We create a simple AJAX handler that returns the current WooCommerce cart contents as JSON.
add_action('wp_ajax_rashed_get_cart_contents', 'rashed_get_cart_contents');
add_action('wp_ajax_nopriv_rashed_get_cart_contents', 'rashed_get_cart_contents');
function rashed_get_cart_contents() {
$cart = WC()->cart->get_cart();
wp_send_json($cart);
}
3. Restore Cart from Cookie
On page load (outside cart/checkout pages), we check if the cart is empty and if a rashed_saved_cart
cookie exists. If so, the items are re-added to the WooCommerce cart.
add_action('template_redirect', 'rashed_restore_cart_from_cookie');
function rashed_restore_cart_from_cookie() {
if ( is_admin() || is_cart() || is_checkout() ) return;
if ( ! is_user_logged_in() && ! WC()->cart->is_empty() ) return;
if ( isset($_COOKIE['rashed_saved_cart']) ) {
$saved_cart = json_decode(stripslashes($_COOKIE['rashed_saved_cart']), true);
if ( is_array($saved_cart) ) {
WC()->cart->empty_cart();
foreach ( $saved_cart as $item ) {
if ( isset($item['product_id']) ) {
WC()->cart->add_to_cart(
$item['product_id'],
$item['quantity'],
$item['variation_id'] ?? 0,
$item['variation'] ?? [],
$item['cart_item_data'] ?? []
);
}
}
// Clear the cookie after restoration
setcookie("rashed_saved_cart", "", time() - 3600, "/");
}
}
}
Why This Matters
This solution is perfect if you want to:
- Recover abandoned carts for guest users
- Improve user experience by preserving their cart
- Simplify return visits and encourage checkout completion
It’s a lightweight enhancement that brings WooCommerce one step closer to the flexibility of modern SaaS platforms — without requiring user logins.
Need help turning this into a plugin or adding session expiration logic?