【问题标题】:Hide a custom button if cart is not empty on ajax add to cart in Woocommerce如果 ajax 上的购物车不为空,则隐藏自定义按钮 添加到 Woocommerce 中的购物车
【发布时间】:2018-10-16 12:23:34
【问题描述】:

我有一个功能可以检查 WooCommerce 购物车是否为空,如果是,则向链接到我的商店页面的页面标题添加一个按钮。但是,此代码仅适用于页面加载,但在通过 AJAX 添加到购物车后不会更新(并删除按钮)。如何检测商品是否已添加到购物车?

function shop_button_when_empty_cart() {

     if ( WC()->cart->get_cart_contents_count() == 0 ) { ?>
         <a href="/shop"><button>Your cart is empty, go to shop</button></a>
     <?php
     }
}
add_action( 'storefront_header', 'shop_button_when_empty_cart', 40 );

【问题讨论】:

    标签: php ajax wordpress button woocommerce


    【解决方案1】:

    如果您使用的是 ajax,那么您将不得不使用 ajax 处理程序。 Woocommerce 有一个名为added_to_cart 的活动 在此事件调用时,您可以在此处注入您的代码,

    $(document).on('added_to_cart',function(){
      //here goes your button add code
    }
    
    $(document).on( 'added_to_cart removed_from_cart', function(){
     //here goes if cart item is removed
    }
    

    【讨论】:

      【解决方案2】:

      基于on this existing answer 这是在添加到购物车按钮上启用 Ajax 的 Woocommerce 存档页面中使其工作的正确方法。在 ajax 添加到购物车时,按钮将被隐藏:

      add_action( 'storefront_header', 'shop_button_when_empty_cart', 40 );
      function shop_button_when_empty_cart() {
      
          $style = WC()->cart->get_cart_contents_count() > 0 ? ' style="display: none;"' : '';
          $class = 'class="button go-shop"';
      
          echo '<a href="/shop" '.$class.$style.'>Your cart is empty, go to shop</a>';
      
          if( is_shop() || is_product_category() || is_product_tag() ):
          ?>
          <script type="text/javascript">
              // Ready state
              (function($){
                  $( document.body ).on( 'added_to_cart', function(){
                      $('a.button.go-shop').hide();
                      console.log('action');
                  });
              })(jQuery);
          </script>
          <?php
          endif;
      }
      

      代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试和工作。

      相关:

      【讨论】:

      • 此解决方案最初有效,但由于页面缓存而损坏。有解决办法吗?
      • @John 此代码有效……页面缓存不在此问题/答案中……
      猜你喜欢
      • 2022-06-10
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 1970-01-01
      • 2015-12-04
      • 1970-01-01
      • 2018-09-30
      相关资源
      最近更新 更多