How to Easily Add AJAX Add to Cart Button on Single Product WooCommerce Pages, for Simple Products

cosmetic products in a cart

A simple code snippet can enhance your single simple product WooCommerce pages with an AJAX add-to-cart button.

NOTE: The code only works for simple products. But, as it checks for the product type, it won’t break other product types. Also, there is one caveat – losing the quantity buttons single product pages usually have.

graphical user interface, application
AJAX add-to-cart button on a single simple product page

AJAX add-to-cart buttons allow the user to add a product to the cart without reloading the page – a faster, more modern experience. While WooCommerce has a built-in ‘Enable AJAX add to cart buttons on archives’ option, it doesn’t have a similar option for single product pages.

Although enabling AJAX add-to-cart on a single product page might not be as beneficial as on archive pages – it can be a nice enhancement nonetheless. Luckily, you can easily add AJAX add-to-cart on single simple product pages, using this code snippet:

add_action('woocommerce_before_single_product', 'remove_woocommerce_template_single_add_to_cart'); function remove_woocommerce_template_single_add_to_cart() { global $product; if ($product->is_type('simple')) { remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30); } } add_action('woocommerce_before_single_product', 'add_woocommerce_template_loop_add_to_cart'); function add_woocommerce_template_loop_add_to_cart() { global $product; if ($product->is_type('simple')) { add_action('woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30); } }
Code language: PHP (php)

The code first checks if the product is a simple product. If it is, the code removes the single add-to-cart button and instead adds the loop add-to-cart button – that is, the archive version of the add-to-cart button. That’s it, the new button magically works! (If it doesn’t, make sure you checked the ‘Enable AJAX add to cart buttons on archives’ WooCommerce setting).

Was the post helpful?

4 responses to “How to Easily Add AJAX Add to Cart Button on Single Product WooCommerce Pages, for Simple Products”

  1. Hi,
    the code works perfectly in single product page just in case you use a “quick add to cart” button otherwise it removes the quantity input field from form and it’s quite annoying if you want to let your visitors buy more than one item at a time.

    • Hi Christian, you are right. It is actually noted at the beginning of the post. It isn’t a perfect solution for all cases. Sorry about that.

  2. Hello! Thank you for posting this. Do you know if is it still working? I tried to copied into my functions.php on my child theme and nothing appears to have changed. I’m not sure if this snippet is still working. Do you have any ideas? Thank you!!!!

Leave a Reply

Your email address will not be published.

%d bloggers like this: