Search code examples
phpwordpresswoocommercecart

How to hide add to cart button in Woocommerce using AJAX IF items already in the cart


I need some help, i have this snippet in wordpress:

    add_action('wp_head', function (){ 
?>
<script>
    jQuery(function($) {
        // Customer click = hide button
        $(".products, .add_to_cart_inline, .added").on("click", function(e) {
            $(".add_to_cart_button.product_type_simple").hide();
        });

        });
    </script>

<?php });

This code is hiding all add to cart button after user clicked it.

My goal: For every item/product that has been added to the cart, the add to cart button is automatically hidden.

Here is a screenshot for what i want to achieve:

Button clicked

Button hidden

Any suggestion?

Thanks in advance!


Solution

  • The script is selecting all the buttons.
    You have to select only the button that is being clicked and hide it.

    Try this script instead. It uses $(this) to select the button clicked.
    Make sure you are selecting the correct button class. Use devtools, for example, to see what class every add button has in common.

    <script>
      jQuery(function($) {
      // Customer click = hide button
        $(".add_to_cart_button").on("click", function(e) {
          $(this).hide();
        });
      });
    </script>