Skip to content

Instantly share code, notes, and snippets.

@psahalot
Created November 14, 2014 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psahalot/507318043c253bd9a298 to your computer and use it in GitHub Desktop.
Save psahalot/507318043c253bd9a298 to your computer and use it in GitHub Desktop.
WooCommerce Add to Cart with AJAX Quantity Input
<?php
// Display an "Add to cart" Button along with "Quantity" input
// for WooCommerce products using a custom Loop
// Reference: https://gist.github.com/webaware/6260468
global $product;
// not for variable, grouped or external products
if (!in_array($product->product_type, array('variable', 'grouped', 'external'))) {
// only if can be purchased
if ($product->is_purchasable()) {
// show qty +/- with button
ob_start();
woocommerce_simple_add_to_cart();
$button = ob_get_clean();
// modify button so that AJAX add-to-cart script finds it
$replacement = sprintf('data-product_id="%d" data-quantity="1" $1 add_to_cart_button product_type_simple ', $product->id);
$button = preg_replace('/(class="single_add_to_cart_button)/', $replacement, $button);
}
}
// output the button
echo $button;
?>
/*** JS for AJAX ***/
<script>
jQuery(function($) {
<?php /* when product quantity changes, update quantity attribute on add-to-cart button */ ?>
$("form.cart").on("change", "input.qty", function() {
$(this.form).find("button[data-quantity]").attr("data-quantity", this.value);
});
<?php /* remove old "view cart" text, only need latest one thanks! */ ?>
$(document.body).on("adding_to_cart", function() {
$("a.added_to_cart").remove();
});
});
</script>
// Create proper function to enqueue JS.
@IaNoz
Copy link

IaNoz commented Feb 20, 2021

Amazing! I have tried many solutions to get Add to cart button with quantity work with AJAX on custom loop. this is the simplest and most effective way. thank you so much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment