Search code examples
htmlwordpresswoocommerceproductcart

How to display a custom button to add a product to the WooCommerce cart?


I need to make a lot of custom buttons that would add products to the cart:

<button type="button" class="button add_to_cart" data-product_id="998" data-quantity="1">
  Add to cart
</button>

The method with the link is very bad and does not work correctly:
https://site-link/?add-to-cart=998&quantity=1

I tried many other options, but nothing worked.


Solution

  • For simple product type, To display an add to cart button, there are multiple ways.

    1. Using an Ajax add to cart button:

      <a href="#" class="button add_to_cart_button ajax_add_to_cart" data-product_id="998" data-quantity="1" rel="nofollow">Add to cart</a>
      
    2. Using POST method with a submit button that requires a surrounding form:

      <form class="cart-custom" method="post">
          <input type="hidden" class="qty" name="quantity" value="1">
          <button type="submit" name="add-to-cart" value="998" class="single_add_to_cart_button button">Add to cart</button>
      </form>
      
    3. Using GET method with a linked button (but it displays the query string in the URL):

      <a href="?add-to-cart=998&quantity=1" class="button add_to_cart_button" rel="nofollow">Add to cart</a>