Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce purchase page add-to-cart with quantity and AJAX, by customising the add-to-cart template in the WooCommerce loop. See blog post for details: http://snippets.webaware.com.au/snippets/woocommerce-add-to-cart-with-quantity-and-ajax/
<?php
/**
* Loop Add to Cart -- with quantity and AJAX
* requires associated JavaScript file qty-add-to-cart.js
*
* @link http://snippets.webaware.com.au/snippets/woocommerce-add-to-cart-with-quantity-and-ajax/
* @link https://gist.github.com/mikejolley/2793710/
*/
// add this file to folder "woocommerce/loop" inside theme
global $product;
if( $product->get_price() === '' && $product->product_type != 'external' ) return;
// script for add-to-cart with qty
wp_enqueue_script('qty-add-to-cart', get_stylesheet_directory_uri() . '/js/qty-add-to-cart.js', array('jquery'), '1.0.1', true);
?>
<?php if ( ! $product->is_in_stock() ) : ?>
<a href="<?php echo get_permalink($product->id); ?>" class="button"><?php echo apply_filters('out_of_stock_add_to_cart_text', __('Read More', 'woocommerce')); ?></a>
<?php else : ?>
<?php
switch ( $product->product_type ) {
case "variable" :
$link = get_permalink($product->id);
$label = apply_filters('variable_add_to_cart_text', __('Select options', 'woocommerce'));
break;
case "grouped" :
$link = get_permalink($product->id);
$label = apply_filters('grouped_add_to_cart_text', __('View options', 'woocommerce'));
break;
case "external" :
$link = get_permalink($product->id);
$label = apply_filters('external_add_to_cart_text', __('Read More', 'woocommerce'));
break;
default :
$link = esc_url( $product->add_to_cart_url() );
$label = apply_filters('add_to_cart_text', __('Add to cart', 'woocommerce'));
break;
}
//printf('<a href="%s" rel="nofollow" data-product_id="%s" class="button add_to_cart_button product_type_%s">%s</a>', $link, $product->id, $product->product_type, $label);
if ( $product->product_type == 'simple' ) {
?>
<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype='multipart/form-data'>
<?php woocommerce_quantity_input(); ?>
<button type="submit" data-quantity="1" data-product_id="<?php echo $product->id; ?>"
class="button alt ajax_add_to_cart add_to_cart_button product_type_simple"><?php echo $label; ?></button>
</form>
<?php
} else {
printf('<a href="%s" rel="nofollow" data-product_id="%s" class="button add_to_cart_button product_type_%s">%s</a>', $link, $product->id, $product->product_type, $label);
}
?>
<?php endif; ?>
/*!
script for WooCommerce add to cart with quantity, via AJAX
Author: support@webaware.com.au
Author URI: http://snippets.webaware.com.au/
License: GPLv2 or later
Version: 1.0.1
*/
// @link http://snippets.webaware.com.au/snippets/woocommerce-add-to-cart-with-quantity-and-ajax/
// @link https://gist.github.com/mikejolley/2793710/
// add this file to folder "js" inside theme
jQuery(function ($) {
/* when product quantity changes, update quantity attribute on add-to-cart button */
$("form.cart").on("change", "input.qty", function() {
if (this.value === "0")
this.value = "1";
$(this.form).find("button[data-quantity]").data("quantity", this.value);
});
/* remove old "view cart" text, only need latest one thanks! */
$(document.body).on("adding_to_cart", function() {
$("a.added_to_cart").remove();
});
});
@dompl

This comment has been minimized.

dompl commented Apr 2, 2015

Thanks!

@graemebryson

This comment has been minimized.

graemebryson commented Apr 10, 2015

Absolutely perfect, thanks man!

@dhavalkakkad

This comment has been minimized.

dhavalkakkad commented Jul 9, 2015

You saved me a day mate. Many thanks. Works like a charm !!

@Oxonium

This comment has been minimized.

Oxonium commented Sep 2, 2015

Same here, thanks a lot, clean and efficient !

@colossss

This comment has been minimized.

colossss commented Oct 1, 2015

Can anyone help? With this code included, I'm now seeing double. It now comes up with 2 "add to cart" and "qty" buttons.

@andrewmclagan

This comment has been minimized.

andrewmclagan commented Dec 11, 2015

This is not the best way to do this, to save client rendering / processing it is better to only perform the check when the "add_to_cart" button is pressed. Not every time the quantity value is changed.

Also much much simpler

        $(".products .product .add_to_cart_button.product_type_simple").on('click', function() {

          var $button = $(this);

          $button.data('quantity', $button.parent('.product').find('input.quantity').val());
        });
@seak3

This comment has been minimized.

seak3 commented Jan 7, 2016

This worked great, thanks a bunch.

@ghost

This comment has been minimized.

ghost commented Feb 8, 2016

AJAX doesn't work anymore after updating to WC 2.5. Add to cart button and quantity selector works fine otherwise but site reloads. Any suggestions how to fix this?

Edit. I solved the problem by adding ajax_add_to_cart class to the button.

@thanewest

This comment has been minimized.

thanewest commented Feb 10, 2016

IPA2, Can you explain further on your fix please? Such as the code snippet and file to edit? Lol... Will be much appreciated by many that see your post I'm sure :D

@graemebryson

This comment has been minimized.

graemebryson commented Feb 14, 2016

@thanewest - not sure if you're still looking for your solution, but I fixed the AJAX issue by adding the '.ajax_add_to_cart' class to the button on line 48 of add-to-cart.php as follows:

<button type="submit" data-quantity="1" data-product_id="<?php echo $product->id; ?>" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple"><?php echo $label; ?></button>

@graemebryson

This comment has been minimized.

graemebryson commented Feb 14, 2016

@webaware - On the first instance of adding products to an empy cart, I'm finding that it's taking a pretty long time (sometimes in excess of 6 seconds), but speeds up when adding further products. Is there a fix for this that you're aware of?

@makdas

This comment has been minimized.

makdas commented Feb 18, 2016

For anyone using the https://docs.woothemes.com/document/minmax-quantities/ plugin. Here's an update to the minimum quantity rule.
on add-to-cart.php line 53:
<form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" class="cart" method="post" enctype='multipart/form-data'> <?php woocommerce_quantity_input(); ?> <?php $minimumamount = get_post_meta( $product->id, 'minimum_allowed_quantity',true ); if(empty($minimumamount)) $minimumamount = 1; ?> <button type="submit" data-quantity="<?php echo $minimumamount ?>" data-product_id="<?php echo $product->id; ?>" class="button alt add_to_cart_button ajax_add_to_cart product_type_simple"><?php echo $label; ?></button> </form>

@coltonbuchanan

This comment has been minimized.

coltonbuchanan commented Feb 22, 2016

I'm able to get AJAX to work with the Add to Cart button, but for some reason changing the product quantity from the archive page loads the single-product template. Anyone know why that would be happening?

Edit: Fixed it. My anchor tag was wrapped around the form. I just added </a> before the form.

@webaware

This comment has been minimized.

Owner

webaware commented Mar 30, 2016

@graemebryson thanks, was just updating a site for this and you saved me some time :)

@webaware

This comment has been minimized.

Owner

webaware commented Mar 30, 2016

@graemebryson re: slow first time, should not be related to this script, probably more related to WooCommerce itself. Do you have a persistent object cache? (e.g. memcached)

@dej888

This comment has been minimized.

dej888 commented Apr 7, 2016

Hello! I just updated to 2.5.5 woocommerce and this is broken now! (it worked fine for 2.5.4)

The problem - It is not adding the items to the cart. You need to refresh the page to get it to show the cart items... Please help, i have been looking for solutions, but am having no luck :(

@priambodokurniawan

This comment has been minimized.

priambodokurniawan commented Apr 26, 2016

Thanks man!! perfect!

@SukcesStrony

This comment has been minimized.

SukcesStrony commented May 19, 2016

Thanks, it worked after a few JS tweaks for the theme I'm using. Acutally, my theme's so FUBAR that I'm using the main code inside mythemedirectory/woocommerce/single-product/add-to-cart/simple.php, at which point it seems that wp_enqueueing isn't possible. So, I had to throw in these lines into functions.php instead of the main code:

// script for add-to-cart with qty
wp_enqueue_script('qty-add-to-cart', get_stylesheet_directory_uri() . '/js/qty-add-to-cart.js', array('jquery'), '1.0.1', true);
@kienhubt

This comment has been minimized.

kienhubt commented May 25, 2016

please help me how to
2nd click , it can remove products from cart

@xnnx

This comment has been minimized.

xnnx commented Jun 7, 2016

Help!
Everything looks fine, but it disregards the quantity input. Only one item is added to the cart. Your help will be greatly appreciated as I'm stuck with this feature for months.
Thank you.

@zavod008

This comment has been minimized.

zavod008 commented Aug 7, 2016

Thanks, its working!

@ibby89

This comment has been minimized.

ibby89 commented Feb 9, 2017

Is there a way to make this work on pages using woocommerce single product shortcodes? It works fine on shop/archive pages but unfortunately I cannot get it to show on a custom page I have...

@0ljik

This comment has been minimized.

0ljik commented Mar 30, 2017

Thanks, it's working but not like I want. First one is that quantity input goes into - numbers. And the second one is I want to have control over it. Like placing it wherever I want: center or in line with button and remove Price tag. I want something like in site plov.com or plov.kz. Please help me do that. I use Widgetkit grid to show products on homepage and I have add to cart button in that grid. Quantity input shows left aligned and button is Centered.

@antoinehenrich

This comment has been minimized.

antoinehenrich commented Nov 17, 2017

When WP_Debug enabled I get 10000 of errors, because get $product->product_type should not be requested in the file.

@braciawrite

This comment has been minimized.

braciawrite commented Mar 15, 2018

It's work but does not send value from input. I have + and - buttons. When I enter the number of works, but that's not the point

@braciawrite

This comment has been minimized.

braciawrite commented Mar 15, 2018

I've rewritten the andrewmclagan code and it works!

$(".add_to_cart_button.product_type_simple").on('click', function() { var $button = $(this); $button.data('quantity', $button.parent().find('input.qty').val()); });

Thanks Bro!

@MoritzSchreiner

This comment has been minimized.

MoritzSchreiner commented Mar 16, 2018

Hi,
Since I updated my page, the function doesn't work anymore.
It always only adds one product to the cart.

Thanks for the help.

@MoritzSchreiner

This comment has been minimized.

MoritzSchreiner commented Mar 16, 2018

@xnnx were you able to fix the issue?

@projecthires

This comment has been minimized.

projecthires commented May 23, 2018

Hi, I would like the quantity selector button only to show on the loop if the product is a certain category. I tried adding this code to replace line 50 in the add-to-cart.php file, but I can't get it to work. Is this the wrong code or am I inserting into the wrong place (or does this just not work)?

if ( $product->product_type == 'simple' && $product->get_category_ids == '19' ) {

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