Search code examples
phpwordpresswoocommercehookcart

Empty cart once a user leaves a certain page in Woocommerce


So we're building a site that has a custom page that's calling the items in a WooCommerce cart. But what we wanted to do is empty that cart once a user leaves that page. Is this possible?

We found this code that will maybe help us but we kept getting a fatal error when we go to the admin page and this only seems to happen when we go to the admin section:

Fatal error: Call to a member function empty_cart() on null in /home/client/public_html/wp-content/themes/wp-theme/functions.php on line 746

This is our code:

add_action( 'init', 'woocommerce_clear_cart_url' );

function woocommerce_clear_cart_url() {
  global $woocommerce;

  if ($_SERVER['REQUEST_URI'] !== 'https://www.oursite.com/fake-cart-page/') {
      $woocommerce->cart->empty_cart();
   }
}

Thank you in advance!


Solution

  • We figured it out! So this is what we did:

    //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 } ?>