【问题标题】:Empty cart once a user leaves a certain page in Woocommerce用户离开 Woocommerce 中的某个页面后清空购物车
【发布时间】:2019-04-04 19:26:26
【问题描述】:

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

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

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

这是我们的代码:

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】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-06
        • 1970-01-01
        • 2018-08-29
        • 2016-03-14
        • 2021-04-27
        • 2014-08-09
        相关资源
        最近更新 更多