Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

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

If the WooCommerce cart is empty, adds a button to the page header that links to my shop page. So Let’s see How to Show custom button on header which link to shop page if cart is empty.

So here is code. add this code in your theme’s functions.php file of your active child theme (or theme).

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

Exit mobile version