Show Ajax Add To Cart Button On Custom Product Loop

Quick Summary
- In a custom WP_Query product loop, echo an add to cart link with the add_to_cart_button and ajax_add_to_cart classes WooCommerce uses.
- Enable AJAX add to cart buttons on archives under WooCommerce > Settings > Products, and set global $product after the_post.
- Variable products get a regular link to the product page, and woocommerce_template_loop_add_to_cart can print the button from WooCommerce's template instead.
WooCommerce’s shop pages come with AJAX add to cart buttons, but in a custom product loop built with WP_Query, such as a loop of products from one category, you have to print the button yourself. This snippet outputs the same markup and classes WooCommerce uses, so its script can add products to the cart without leaving the page.
Step 1: enable AJAX buttons
In WooCommerce > Settings > Products, turn on Enable AJAX add to cart buttons on archives. With this setting on, WooCommerce loads the script that handles clicks on these buttons.
Step 2: print the button in your loop
Add this code inside your loop, where the Add to Cart button should appear:
<?php
echo sprintf('<a href="%s" data-quantity="1" class="%s" %s>%s</a>', esc_url($product->add_to_cart_url()), esc_attr(implode(' ', array_filter(array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports('ajax_add_to_cart') ? 'ajax_add_to_cart' : ''
)))), wc_implode_html_attributes(array(
'data-product_id' => $product->get_id(),
'data-product_sku' => $product->get_sku(),
'aria-label' => $product->add_to_cart_description(),
'rel' => 'nofollow'
)), esc_html($product->add_to_cart_text()));
?>$productmust hold the current product. In a custom loop, addglobal $product;afterthe_post(), or load it withwc_get_product( get_the_ID() ).- The
hrefcomes fromadd_to_cart_url(), so for simple products the link still adds the product to the cart when JavaScript is off. - The
ajax_add_to_cartclass is only added when the product type supports it, such as simple products. Variable products get a regular button that leads to the product page, where customers choose options. data-product_idanddata-quantitytell the script which product to add and how many.- The button text and
aria-labelcome from WooCommerce, so they match the rest of your store.
If you’d rather not keep this markup in your theme, WooCommerce’s woocommerce_template_loop_add_to_cart() prints the button from its own template.
Related articles
- updating the header cart count after an AJAX add to cart: so the header reflects the new item
- stopping the redirect when an AJAX add to cart fails: keeps shoppers on the page when adding fails
- printing the product price in a custom loop: the price for the same product card
