Taylor
Taylor

Reputation: 365

Hide a custom button if cart is not empty on ajax add to cart in Woocommerce

I have a function that checks if the WooCommerce cart is empty, and if it is, adds a button to the page header that links to my shop page. However, this code only works on page load, but won’t update (and remove the button) after adding to cart via AJAX. How do I detect if an item has been added to the cart?

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

Upvotes: 0

Views: 2064

Answers (2)

LoicTheAztec
LoicTheAztec

Reputation: 253901

Based on this existing answer here is the correct way to make this work in Woocommerce archive pages where Ajax is enabled on add to cart button. On ajax add to cart the button will be hidden:

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

Code goes in function.php file of your active child theme (or active theme). tested and work.

Related:

Upvotes: 1

Sajjad Hossain Sagor
Sajjad Hossain Sagor

Reputation: 518

If you are using ajax then you will have to use ajax handler. Woocommerce have an event called added_to_cart Here you can inject your code when this event is calling,

$(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
}

Upvotes: 0

Related Questions