0

I'm customising a default template in Woocommerce in order to display an AJAX add to cart button which dynamically pulls the product ID, using this code:

/**
 * Customise variable add to cart button for loop.
 *
 * Remove qty selector and simplify.
 */
function iconic_loop_variation_add_to_cart_button() {
    global $product;
    ?>
    <div class="woocommerce-variation-add-to-cart variations_button">
        <input type="hidden" name="add-to-cart" value="<?php echo absint( $product->get_id() ); ?>" />
        <input type="hidden" name="product_id" value="<?php echo absint( $product->get_id() ); ?>" />
        <input type="hidden" name="variation_id" class="variation_id" value="0" />
        <button type="submit" class="single_add_to_cart_button button"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>
    </div>
    <?php
}

This works to add an item to the cart, however because it is using a submit button it forces the page to refresh instead of adding the item to the cart via AJAX. I believe if I convert the button to an <a> tag with all the correct properties (product ID including in the data-attributes parameters and a href containing '?add-to-cart=ID' like other Woocommerce buttons then it should add items via AJAX.

I've pieced this together below:

<a href="<?php echo "?add-to-cart=".$product->get_id(); ?>" class="single_add_to_cart_button button"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></a>

When included in place of the button, this returns an add to cart button with the URL https://example.com/shop/?add-to-cart=853 which is the correct dynamic ID, however when clicking the button the page hard reloads and the product is not updated in the cart. In Console it looks like the data-attributes are missing so I'm assuming that's why but I could be wrong.

Can anyone help me to understand the correct method to achieve this outcome and what I need to replace the submit button with in order to return an AJAX 'add to cart' button which dynamically pulls the product ID for each item?

van
  • 158
  • 1
  • 2
  • 12
  • This has little to do with button vs link. It depends on whether the proper JavaScript event handlers are added to the element in question, to intercept the click and the associated default functionality (form submit, or loading of new page), and make an AJAX request instead. The default button appears to not do this on its own, but there are plugins available to easily add this functionality, like https://de.wordpress.org/plugins/woo-ajax-add-to-cart/ – CBroe Mar 09 '22 at 13:59
  • https://stackoverflow.com/questions/25892871/woocommerce-product-page-how-to-create-ajax-on-add-to-cart-button could also be helpful here. – CBroe Mar 09 '22 at 14:00
  • @CBroe thanks! This answer (https://stackoverflow.com/a/61058748/10084649) is so painfully close to working, the problem is it doesn't pass the variation of the product to the cart page - any ideas? – van Mar 09 '22 at 14:19

0 Answers0