用户离开 Woocommerce 中的某个页面后清空购物车

Empty cart once a user leaves a certain page in Woocommerce

所以我们正在构建一个网站,该网站有一个自定义页面,该页面调用 WooCommerce 购物车中的项目。但是我们想要做的是在用户离开该页面后清空该购物车。这可能吗?

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

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

这是我们的代码:

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

提前致谢!

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

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

谢谢!这对我也有用!我使用了一个名为“Insert PHP Code Snippet”的插件,它可以让你用代码创建一个短代码——在这种情况下,我复制并粘贴了上面的代码,并将页面 ID 更改为我结帐页面的页面 ID。然后,在结帐页面上,我插入了简码。非常感谢!