I got this code to clear cart and it’s working perfectly for logged-in users but not guests. For guests, I have to leave the checkout page and load another page to clear the cart.
How to auto empty cart when leaving checkout for registered customers and guest?
This is the code (picked from stack overflow):
<?php
//we inserted a script in wordpress and put it in the head
add_action('wp_head', 'woocommerce_clear_cart_url');
function woocommerce_clear_cart_url()
{
global $woocommerce;
//we used the jquery beforeunload function to detect if the user leaves that page
?>
<script>
jQuery(document).ready(function($) {
$(window).bind('beforeunload', function() {
//Used WordPress to help jQuery determine the page we're targeting
//pageID is the page number of the page we're targeting
<?php if (!is_page(pageID)):
//empty the cart
$woocommerce->cart->empty_cart(); ?>
<?php endif; ?>
});
});
</script>
<?php } ?>
2
Answers
For this you can try it by pure php code. In this you would required
template_redirect
hook.Add below code in function.php
Note: Please ensure you have done fast checkout once product gets added to cart directly send them to checkout page. So this could make more sence.
It looks like your code is partially working but not fully clearing the cart for guest users when they leave the checkout page. To ensure both logged-in users and guests experience the same functionality, there are a couple of key changes we can make.
Issues with the Current Code:
Guest Users: The current script only clears the cart after the guest loads another page. This is because the code runs server-side and waits for a new page to be loaded.
Use of beforeunload Event: While beforeunload is used, it’s not an ideal solution because it doesn’t consistently fire or perform the action fast enough before a user leaves the page.
Suggested Solution
We can make some modifications to your code to properly clear the cart for both registered users and guests. One approach is to send an AJAX request when the user leaves the checkout page, which works better than using beforeunload. Here’s a working solution:
You can follow this method from this post.
https://howtoinwordpress.com/how-to-automatically-clear-cart-when-users-leave-the-checkout-page-in-wordpress/