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?