Empty cart once a user leaves a certain page in Woocommerce

萝らか妹 提交于 2020-06-29 04:33:46

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/53086584/empty-cart-once-a-user-leaves-a-certain-page-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!