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

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.

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’ WooCommerse setting).

Leave a comment

Your email address will not be published. Required fields are marked *