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
<?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()));
?>
  • $product must hold the current product. In a custom loop, add global $product; after the_post(), or load it with wc_get_product( get_the_ID() ).
  • The href comes from add_to_cart_url(), so for simple products the link still adds the product to the cart when JavaScript is off.
  • The ajax_add_to_cart class 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_id and data-quantity tell the script which product to add and how many.
  • The button text and aria-label come 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.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More