The hook for the AJAX Add to Cart button?

Digging through the code, it’s pretty straight-forward to find.

First, look at the template used for product archives – /templates/archive-product.php. Among other things, it sets up the regular queries and begins building the markup of the page.

But when it actually starts looping through each product, it delegates the work to /templates/loop-shop.php. This template is loaded for every product, and builds a listing using the following code:

<?php do_action('woocommerce_before_shop_loop_item'); ?>
        
<a href="<?php the_permalink(); ?>">
            
    <?php do_action('woocommerce_before_shop_loop_item_title', $post, $_product); ?>
            
    <h3><?php the_title(); ?></h3>
            
    <?php do_action('woocommerce_after_shop_loop_item_title', $post, $_product); ?>
        
</a>

<?php do_action('woocommerce_after_shop_loop_item', $post, $_product); ?>

The part we care about is the last action: woocommerce_after_shop_loop_item. It’s wired in /woocommerce_template_actions.php to the function woocommerce_template_loop_add_to_cart().

Digging even deeper, and it looks like this function is the one you need.

How to Add It

The easiest way to use this function is to call it directly. Just know that it requires to parameters, $post and $_product. The following code would call it just fine:

global $post; // Assuming it's already set up
$_product = &new woocommerce_product( $post->ID );

woocommerce_template_loop_add_to_cart( $post, $_product );

The function itself calls its own echos, so just call it directly.

Leave a Comment