Question: 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!

Answer: 
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 } ?>

```
Thanks! this worked for me as well! I used a plugin called "Insert PHP Code Snippet", which lets you create a shortcode with code - in this case I copied and pasted the code above, and changed the page ID to the page ID of my checkout page. Then, on the checkout page, I inserted the shortcode. Thanks so much!