Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce - Template add-to-cart.php with quantity and Ajax!
<?php
/**
* Custom Loop Add to Cart.
*
* Template with quantity and ajax.
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly.
global $product;
?>
<?php if ( ! $product->is_in_stock() ) : ?>
<a href="<?php echo apply_filters( 'out_of_stock_add_to_cart_url', get_permalink( $product->id ) ); ?>" class="button"><?php echo apply_filters( 'out_of_stock_add_to_cart_text', __( 'Read More', 'woocommerce' ) ); ?></a>
<?php else : ?>
<?php
$link = array(
'url' => '',
'label' => '',
'class' => ''
);
switch ( $product->product_type ) {
case "variable" :
$link['url'] = apply_filters( 'variable_add_to_cart_url', get_permalink( $product->id ) );
$link['label'] = apply_filters( 'variable_add_to_cart_text', __( 'Select options', 'woocommerce' ) );
break;
case "grouped" :
$link['url'] = apply_filters( 'grouped_add_to_cart_url', get_permalink( $product->id ) );
$link['label'] = apply_filters( 'grouped_add_to_cart_text', __( 'View options', 'woocommerce' ) );
break;
case "external" :
$link['url'] = apply_filters( 'external_add_to_cart_url', get_permalink( $product->id ) );
$link['label'] = apply_filters( 'external_add_to_cart_text', __( 'Read More', 'woocommerce' ) );
break;
default :
if ( $product->is_purchasable() ) {
$link['url'] = apply_filters( 'add_to_cart_url', esc_url( $product->add_to_cart_url() ) );
$link['label'] = apply_filters( 'add_to_cart_text', __( 'Add to cart', 'woocommerce' ) );
$link['class'] = apply_filters( 'add_to_cart_class', 'add_to_cart_button' );
} else {
$link['url'] = apply_filters( 'not_purchasable_url', get_permalink( $product->id ) );
$link['label'] = apply_filters( 'not_purchasable_text', __( 'Read More', 'woocommerce' ) );
}
break;
}
// If there is a simple product.
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
// Displays the quantity box.
woocommerce_quantity_input();
// Display the submit button.
echo sprintf( '<button type="submit" data-product_id="%s" data-product_sku="%s" data-quantity="1" class="%s button product_type_simple">%s</button>', esc_attr( $product->id ), esc_attr( $product->get_sku() ), esc_attr( $link['class'] ), esc_html( $link['label'] ) );
?>
</form>
<?php
} else {
echo apply_filters( 'woocommerce_loop_add_to_cart_link', sprintf('<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="%s button product_type_%s">%s</a>', esc_url( $link['url'] ), esc_attr( $product->id ), esc_attr( $product->get_sku() ), esc_attr( $link['class'] ), esc_attr( $product->product_type ), esc_html( $link['label'] ) ), $product, $link );
}
?>
<?php endif; ?>
<?php
function cs_wc_loop_add_to_cart_scripts() {
if ( is_shop() || is_product_category() || is_product_tag() || is_product() ) : ?>
<script>
jQuery( document ).ready( function( $ ) {
$( document ).on( 'change', '.quantity .qty', function() {
$( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );
});
});
</script>
<?php endif;
}
add_action( 'wp_footer', 'cs_wc_loop_add_to_cart_scripts' );
@karpstrucking

This comment has been minimized.

Copy link

@karpstrucking karpstrucking commented Oct 5, 2013

Exactly what I needed, thank you!

@sail1987

This comment has been minimized.

Copy link

@sail1987 sail1987 commented Dec 28, 2013

Actually i tried the above step by adding them to add-to-cart.php file but it didnt work....please help on this...

@Robzelf

This comment has been minimized.

Copy link

@Robzelf Robzelf commented May 5, 2014

Great stuff, works fine for me!

@rubentomas

This comment has been minimized.

Copy link

@rubentomas rubentomas commented May 13, 2014

it works.

but it dont affect my "single product" page.

how can i make this snipet work in my single page?

@pravinsinghthakuri

This comment has been minimized.

Copy link

@pravinsinghthakuri pravinsinghthakuri commented May 19, 2014

thanks for the code, works perfectly. but there is some issue
Each time you add product it appends on previous quantity i needs it to update cart with latest quantity., also when u add 0 products it says 1 product added.

regards

@brendan-f

This comment has been minimized.

Copy link

@brendan-f brendan-f commented Mar 5, 2015

Great loop! Saved me a ton of time, thanks.

@jennylu89

This comment has been minimized.

Copy link

@jennylu89 jennylu89 commented Mar 20, 2015

Hello, thanks for the code, for some reason the quantity is not matching the input.

The only takes the first initial input, if I update the input to something else, it keeps adding the initial number. Any help?

@mrgarry05

This comment has been minimized.

Copy link

@mrgarry05 mrgarry05 commented May 26, 2015

Almost Perfect, only issue is i got another plugin for variable products which show option selection box, quantity selection box and of course an Add to cart Button as well, but color, size, position of add to cart button is not exactly like on single product page and under the variable product page , how could i fix that . have a look at screenshot here http://tinypic.com/r/a4o6t0/8

@ignacioazzi

This comment has been minimized.

Copy link

@ignacioazzi ignacioazzi commented Sep 27, 2015

mrgarry05,
Could you share that plugin you mention?

@neutch

This comment has been minimized.

Copy link

@neutch neutch commented Jan 1, 2016

This is generating errors on server running php5.4

( ! ) WARNING: ILLEGAL STRING OFFSET 'CLASS' IN /MEDIA/DATA/WWW/DEV-PALEOBOXMEALS/WP-CONTENT/THEMES/JUPITER/WOOCOMMERCE/CONTENT-PRODUCT.PHP ON LINE 219

It's referencing this line:
echo sprintf('%s', esc_attr( $product->id ), esc_attr( $product->get_sku() ), esc_attr( $link['class'] ), esc_html( $link['label'] ) );

Any Ideas? I have read that these offset errors are common on PHP 5.4 but not exactly sure how to fix it, any help would be appreciated!

@Shamjithv

This comment has been minimized.

Copy link

@Shamjithv Shamjithv commented Jan 28, 2016

I have used the above code and thank you for this. But i could not get the product variable option in the product single page, if the product type is "Variable Product". So i have changed two lines and it is working fine now.

switch ( $product->product_type ) {
case "variable" :
$link = apply_filters( 'variable_add_to_cart_url', get_permalink( $product->id ) );
$label = woocommerce_variable_add_to_cart();
break;

@ptrsmk

This comment has been minimized.

Copy link

@ptrsmk ptrsmk commented Feb 26, 2016

Not working on latest woocommerce (tested with storefront theme).

@alcris

This comment has been minimized.

Copy link

@alcris alcris commented Feb 28, 2016

It worked verry fine but i upgrade woocommerce and it not working now :(
With latest woocommerce and storefront, it not work
Please help me if you can

@ebelrose

This comment has been minimized.

Copy link

@ebelrose ebelrose commented Mar 1, 2016

Since 2.5.2 you have to add .ajax_add_to_cart css class to your link.
See here woocommerce/woocommerce@856d192

@MonteroJJ

This comment has been minimized.

Copy link

@MonteroJJ MonteroJJ commented Mar 26, 2016

Yes, as ebelrose said. In your add_to_cart.php you must replace "product_type_simple" with "ajax_add_to_cart" and it works.
Thank you very much, it worked great for me. (btw im not sure this is the correct solution, but it works for me)

@raczosala

This comment has been minimized.

Copy link

@raczosala raczosala commented Apr 10, 2016

WooCommerce add-to-cart.js uses jQuery data() function, in order to avoid cache issues update the quantity attribute with the data() function.

Use this:
$( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).data( 'quantity', $( this ).val() );

Instead of this
$( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );

@clestcruz

This comment has been minimized.

Copy link

@clestcruz clestcruz commented Apr 23, 2016

I'm building a custom e-commerce website using woocommerce and I'm having some trouble fixing the "add to cart button". Whenever I add the multiple amounts it only increments or adds one item to the cart. This only happens when I create custom loop to query woocommerce products

On the shop and single-product page, it works fine. If I add 10 items and press the add to cart button. It exactly adds 10 items to the cart.

Here is the code I have been working on. I really don't know why it only increments one item to the cart. I tried applying ebelrose, raczosala and MonteroJJ and still the same output

    <?php
    $args = array(
        'post_type' => 'product',
    );
    $crate_products = new WP_Query($args);

    if ($crate_products->have_posts()):
        while ($crate_products->have_posts()):
            $crate_products->the_post();
    ?>

                <div id="post-<?php
            the_ID() ?>" class="three columns product-post">

                <?php  wc_get_template_part('content', 'product'); ?>

                </div>

                <?php
            wp_reset_postdata(); ?>

                <?php
        endwhile;
      else : ?>

                <?php
    endif; ?>

                <?php
    wp_reset_query(); ?>
@Lewiscowles1986

This comment has been minimized.

Copy link

@Lewiscowles1986 Lewiscowles1986 commented May 6, 2016

Interested to know what you make of an alternative approach here. Also be interested to know if Ajax could be implemented in core WC?

@lukecav

This comment has been minimized.

Copy link

@lukecav lukecav commented Sep 17, 2016

So it does work just the add to cart filter for variable products have changed.

Variable
woocommerce_variable_add_to_cart

Simple
woocommerce_loop_add_to_cart_link

So if you do change the variable apply filter it will work.

@lukecav

This comment has been minimized.

Copy link

@lukecav lukecav commented Sep 17, 2016

So you can use this filter to remove the select options variable add to cart text.

http://hookr.io/filters/variable_add_to_cart_text/

// remove the filter 
remove_filter( 'variable_add_to_cart_text', 'filter_variable_add_to_cart_text', 10, 3 );

@SarahMouse

This comment has been minimized.

Copy link

@SarahMouse SarahMouse commented Sep 19, 2016

Does anyone know how you can adapt this code so that the page does not refresh after adding the product to the cart? Is anyone else having the same problem?

@mhasanenosis

This comment has been minimized.

Copy link

@mhasanenosis mhasanenosis commented Jul 30, 2017

Quantity input box is displaying but cart is not updating with the qty.

@sepisoltani

This comment has been minimized.

Copy link

@sepisoltani sepisoltani commented May 19, 2018

it just works on simple product . it has problem with variable products . button shows but dosn't add the product to cart.
whats the reason?

@steveo2001

This comment has been minimized.

Copy link

@steveo2001 steveo2001 commented Jun 5, 2018

@raczosala your comment on 10 Apr 2016 fixed my problem I had when I added a qty box and add to cart button when clicking a second time the original qty got used. I was using .attribute, rather than .data - Thank you for helping!! :)

@saqiibsarfraz

This comment has been minimized.

Copy link

@saqiibsarfraz saqiibsarfraz commented Sep 30, 2018

I used the code and it works but my page refreshes every time I press the add to cart button. Can anyone help?
mayvaa just another wordpress site

@zzhenryquezz

This comment has been minimized.

Copy link

@zzhenryquezz zzhenryquezz commented Feb 23, 2019

This Help a lot, thanks

@josephbrundige

This comment has been minimized.

Copy link

@josephbrundige josephbrundige commented Mar 22, 2019

THIS IS AWESOME. THANK YOU SO MUCH

@fastmarketo

This comment has been minimized.

Copy link

@fastmarketo fastmarketo commented Sep 20, 2019

In plugin where is this template → add-to-cart.php?

@Laurynas-3D

This comment has been minimized.

Copy link

@Laurynas-3D Laurynas-3D commented Nov 10, 2020

Hi,
Is there a working solution for this quantity with ajax method with WooCommerce 4?

@cmoosbrugger3264

This comment has been minimized.

Copy link

@cmoosbrugger3264 cmoosbrugger3264 commented Mar 3, 2021

Hi,

is there a working solution for variable products? It is working for single products but not for variable.

thanks

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