用户在Woocommerce中离开某个页面时清空购物车

问题描述 投票:0回答:1

因此,我们正在构建一个网站,其中包含一个调用WooCommerce购物车中的商品的自定义页面。但是,一旦用户离开该页面,我们想要做的就是清空该购物车。这可能吗?

我们发现这段代码可能会对我们有所帮助,但是当我们进入管理页面时,我们仍然会遇到致命的错误,而这似乎只有在我们进入管理部分时才会发生:

致命错误:在第746行的empty_cart()中调用null成员函数/home/client/public_html/wp-content/themes/wp-theme/functions.php

这是我们的代码:

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();
   }
}

先感谢您!

php wordpress woocommerce hook cart
1个回答
1
投票

我们想通了!所以这就是我们做的:

//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 } ?>
© www.soinside.com 2019 - 2024. All rights reserved.