Out of the box WooCommerce displays an Add to Cart button on product archive pages, but does not have the quantity input. There are a few solutions out there to achieve this, but none maintain ajax functionality (which is very handy on archive pages). Thankfully it’s super easy to get this up and running.
First, drop the following code to your functions.php file (remembering to remove the opening <?php tag), and WooCommerce will print out a nice quantity input box next to your add_to_cart button.
This isn’t the end of the story, as it won’t do anything by itself. To send a quantity along with the add_to_cart ajax request, we can add a custom data attribute to the add_to_cart button called data-quantity. With this data attribute set, WooCommerce will handle the quantity automatically. This means all we need to do is add a little bit of javascript to update this data attribute when the quantity input is changed. This can be achieved with the following javascript (put this in your websites main javascript file, inside the $.ready() function).
*Note: This works with WooCommerce’s default HTML structure, but if you’re using a custom theme the HTML structure might be different, so you’ll need to modify this script to suit.
And that’s it! These two small snippets are all you need to add a quantity input to archived product pages and maintain ajax functionality. If you’d like a dynamic cart on your page that updates when you add products via ajax, WooCommerce has already got you covered here: http://docs.woothemes.com/document/show-cart-contents-total/.
If this post has helped you out, feel free to consider throwing a small donation my way.
Comments are closed.
29 comments
Hi Christian, can you please share a solution for the variable products quantity input field and buttons with ajax? for some reason WooCommerce 4 broke a lot of code in the stackoverflow and there is fixes upon fixes.
Hi Christian,
Thank you for great solution, is there any way we can display variations and quantity like this way on archives page.
So existing customers who wants to order dont need to open product page all the time, thanks in advance
If someone manually enters in a number greater than the “max amount” it directs them to the product page. Any way to interject a warning saying they can only enter in the max amount before loading the product page?
Hi all,
How can we set dafault product quantity 4 on single page nad it will update multiply by 4….8…12..16….20…24…28…etc
where do i have to put this if i dont have application.js on my theme
$(‘.input-text.qty’, ‘ul.products’).on(‘input’, function() {
$(this).closest(‘li’).find(‘.add_to_cart_button’).data(‘quantity’, $(this).val());
});
You can put it in any javascript file as long as it’s included on the archive page. Alternatively, you can look for a plugin that allows you to inject javascript into the page, such as Simple Custom CSS and JS.
Hello Christia, can you hel me out?
I created a file like this https://gist.github.com/levymetal/8412bb4f4f1c4dbaa184
and added the following lines to my function.php file
wp_enqueue_script( ‘application’, get_stylesheet_directory_uri() . ‘/js/lib/application.js’, array( ‘jquery’ ) );
but it doesn’t seem to work. it only add 1 quantity to the cart.
I am really not good in coding and if you can hel me out it would be highly appreciated.
thank you very much
The only way I can assist is if I have access to all of your code. There are a million different reasons why this might not be working, so if I can’t see all of your code, unfortunately I won’t be able to assist.
Thank you very much for your reply.
May i send you a PM or email to give you access?
My contact details are on the about page. I’ll need access to WordPress & FTP.
Thank you Christian. Pretty straight forward solution. Peace.
Hi, this is exactly what I have been searching for. Got the function bit working, but have no idea where to put the Javascript. Im using Woo Canvas as my theme. Any pointers would be greatly appreciated
There javascript doesn’t need to go in any specific file; it can go in any javascript file of your choosing. If you’ve created a child theme for Woocanvas, just create a new javascript file and enqueue it: http://codex.wordpress.org/Function_Reference/wp_enqueue_script. Alternatively, I’m sure there are plugins that allow you to add javascript snippets to your site.
Cheers for the amazingly quick answer. I tried adding that code to the general.js file which was in the themes include folder. This was the only place I found the .ready(function() but this hasnt worked for some reason. I will try doing what you suggest. Do I create a .js file with the .ready function and code and then enqueue it. Thanks mate
No worries mate! Yeah just create a file like this: https://gist.github.com/levymetal/8412bb4f4f1c4dbaa184. Then enqueue it.
If it doesn’t work, let me know (and if you can link me to your website, that would be great). My post is quite old, and WooCommerce had a major update recently, so the javascript might need slight tweaking to work with the new version.
Hi Christian, This is the site http://trade.craftedlines.co.uk/product-catalogue/
I have the latest Woocommerce installed.
What I did was create a child theme and in this theme created a folder called js and inside this I created a file called addtocartarchive.js with this code in it
jQuery(function($) {
$(‘.input-text.qty’, ‘ul.products’).on(‘change’, function() {
$(this).closest(‘div’).next(‘a’).attr(‘data-quantity’, $(this).val());
});});
Then added this to my functions file :
/**
* Proper way to enqueue scripts and styles
*/
function theme_name_scripts() {
wp_enqueue_style( ‘style-name’, get_stylesheet_uri() );
wp_enqueue_script( ‘script-name’, get_template_directory_uri() . ‘/wp-content/themes/canvascrafted/js/addtocartarchive.js’, array(), ‘1.0.0’, true );
}
add_action( ‘wp_enqueue_scripts’, ‘theme_name_scripts’ );
But its not working. Any help most appreciated. Will buy you a beer if you can shed light on where I have gone wrong.
First step of debugging is to check if the files are being loaded. Viewing the source of your website shows that the path to your js file is http://trade.craftedlines.co.uk/wp-content/themes/canvas/wp-content/themes/canvascrafted/js/addtocartarchive.js, which is not the correct path.
Check the codex carefully (especially the part about child themes). You should actually be enqueuing the javascript files like this:
wp_enqueue_script( 'addtocartarchive', get_stylesheet_directory_uri() . '/js/addtocartarchive.js', array( 'jquery' ) );
Note the use of get_stylesheet_directory_uri(). This automatically gets the path of your theme, so you don’t have to manually specify it. It’s also a good idea to add jQuery as a dependency.
Fantastic, got it working. Created a functions.php file in my child theme and enclosed that script with PHP
Thanks for your help. Whats your paypal, I will send you a beer cheers Andy.. This should be a plug, bet you would sell a few.
Awesome stuff, glad to see the code still works with the latest version of WooCommerce. I’m too lazy to make a plugin, prefer just to give it away for free :p.
Thanks for the offer mate! PayPal deets can be found at the end of my post, or here: https://christianvarga.com/donate/
Beer sent.
Cheers! Have a great weekend mate.
Your code is really simple, unobtrusive, and works like a charm. Too bad it took me 48 hours of Googling and trying to work out a solution myself before I found your post. Google really needs to connect your post with people searching for how to add products to cart with AJAX in Woocommerce. I hope they figure that out somehow….
So anyway, two questions. First, I have variable and simple products and it makes sense to not display a simple quantity select box for something that requires the user to choose options. Can you think of a way to only show qty box on archive pages for simple products or products for which the button is only “add to cart” and not “select options” or “read more”?
Second, can you think of a way to apply ajax add to cart to product pages themselves, and not just archives? I am amazed this doesn’t already exist, but here we are. Seems to me there should be an option to ajax add items to cart from anywhere, not just archives.
Thanks again for the easy solution to part of my add to cart with ajax issue. Google really needs to get on the ball. I tried dozens of other pages with what turned out to be pretty much useless information before stumbling on your post.
Figured out part 1 of my question…
if ( $product->is_type(‘simple’) && ! $product->is_sold_individually())
I’m really glad this has helped you out, it struggled with it for a long time and I couldn’t believe that a solution hadn’t already been developed. Hopefully in the future this page makes its way up the Google rankings so it can help more people out.
I’ve actually had to deal with both of the problems you’re having too. I see you’ve already solved part one, I did it the exact same way as you. For the second part, unfortunately I can’t help you right now as I’m on holiday for a couple of weeks. But from memory Woocommerce has 2 different templates for displaying the Add to Cart button – one for archives (loop/add-to-cart.php) and one for single products (single-product/add-to-cart/simple.php). So I think I just created copies of all the files in the single-product/add-to-cart folder in my own theme, then used the loop/add-to-cart.php code inside of them. Or perhaps I hooked those buttons up to the ajax functionality using a bit of javascript. I can’t quite remember. Anyway, if you don’t figure it out in a couple weeks, I’ll get back to you with how I did it.
Hello Christian, Where I have to add this code?
$(‘.input-text.qty’, ‘ul.products’).on(‘change’, function() {
$(this).closest(‘div’).next(‘a’).attr(‘data-quantity’, $(this).val());
});
You just need to put that in any javascript file you control, inside the $.ready function. There’s plenty of tutorials out there on how to add javascript to your theme, try here and here, or if all else fails, try asking a question on Stack Overflow.
Thank you, your code and explanation has helped me greatly. I actually used a bit simpler PHP/HTML code and placed them in the template files (a bit raw, i know) rather than using hooks.
Display the Quantity box:
is_sold_individually() )
woocommerce_quantity_input( array( ‘min_value’ => 1, ‘max_value’ => $product->backorders_allowed() ? ” : $product->get_stock_quantity() ) ); ?>
Display the Add Cart button:
<button type="submit" id="button-ajax-add" data-quantity="1" data-product_id="id; ?>” class=”button alt add_to_cart_button product_type_simple” style=”float:none;margin:0px auto;”>add_to_cart_text() ); ?>
My Add Cart button was sitting inside of the Parents Parents’ container, so modified jQuery to suit:
$(‘.input-text.qty’).on(‘change’, function() {
$(this).parent().parent().find(‘button’).attr(‘data-quantity’, $(this).val());
});