首页 文章

如果在ajax上购物车不为空,则隐藏自定义按钮添加到Woocommerce中的购物车

提问于
浏览
0

我有一个功能,检查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 );

2 回答

  • 1

    基于on this existing answer这是在Woocommerce存档页面中使用此功能的正确方法,其中在添加到购物车按钮时启用了Ajax . 在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文件中 . 经过测试和工作 .

    有关:

  • 0

    如果您使用的是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
    }
    

相关问题