WooCommerce: Change Add to Cart Quantity into a Select Drop-down

The default WooCommerce Add to Cart “Quantity Input” is a simple input field where you can enter the number of items or click on the “+” and “-” to increase/reduce the quantity.

A freelance client hired me to turn that input into a “Select” drop-down. For their audience and UX requirements, it makes sense to let their customers choose the quantity from a drop-down instead of having to manually input the number.

Online there are complex snippets, but I decided to make things easier. The WooCommerce function responsible to generate the quantity input is called “woocommerce_quantity_input“.

Luckily, it’s a pluggable function – which means we can simply add this exact same function name to our child theme’s functions.php to completely override it. Enjoy!

WooCommerce: turn Add to Cart Quantity input into a select drop-down

PHP Snippet: Turn Add to Cart “Quantity” into a select drop-down – WooCommerce

Note: this, and all pluggable function overrides. won’t work in the Code Snippets plugin. Yet another reason to get all your custom code in a child theme instead.

/**
 * @snippet       Add to Cart Quantity drop-down - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 8
 * @community     https://businessbloomer.com/club/
 */
 
function woocommerce_quantity_input( $args = array(), $product = null, $echo = true ) { 
	if ( is_null( $product ) ) {
	   $product = $GLOBALS['product'];
	}
	$defaults = array(
		'input_id' => uniqid( 'quantity_' ),
		'input_name' => 'quantity',
		'input_value' => '1',
		'classes' => apply_filters( 'woocommerce_quantity_input_classes', array( 'qty', 'text' ), $product ),
		'max_value' => apply_filters( 'woocommerce_quantity_input_max', -1, $product ),
		'min_value' => apply_filters( 'woocommerce_quantity_input_min', 0, $product ),
		'step' => apply_filters( 'woocommerce_quantity_input_step', 1, $product ),
		'pattern' => apply_filters( 'woocommerce_quantity_input_pattern', has_filter( 'woocommerce_stock_amount', 'intval' ) ? '[0-9]*' : '' ),
		'inputmode' => apply_filters( 'woocommerce_quantity_input_inputmode', has_filter( 'woocommerce_stock_amount', 'intval' ) ? 'numeric' : '' ),
		'product_name' => $product ? $product->get_title() : '',
	);
	$args = apply_filters( 'woocommerce_quantity_input_args', wp_parse_args( $args, $defaults ), $product ); 
	// Apply sanity to min/max args - min cannot be lower than 0.
	$args['min_value'] = max( $args['min_value'], 0 );
	// Note: change 20 to whatever you like
	$args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : 20;
	// Max cannot be lower than min if defined.
	if ( '' !== $args['max_value'] && $args['max_value'] < $args['min_value'] ) {
		$args['max_value'] = $args['min_value'];
	} 
	$options = '';	
	for ( $count = $args['min_value']; $count <= $args['max_value']; $count = $count + $args['step'] ) {
	   // Cart item quantity defined?
	   if ( '' !== $args['input_value'] && $args['input_value'] >= 1 && $count == $args['input_value'] ) {
		  $selected = 'selected';      
	   } else $selected = '';
	   $options .= '<option value="' . $count . '"' . $selected . '>' . $count . '</option>';
	} 
	$string = '<div class="quantity"><label for="' . esc_attr( $args['input_id'] ) . '">' . esc_html__ ( 'Qty', 'woocommerce' ) . '</label><select id="' . esc_attr( $args['input_id'] ) . '" name="' . $args['input_name'] . '" class="'. esc_attr( join( ' ', (array) $args['classes'] ) ) . '">' . $options . '</select></div>';
	if ( $echo ) {
	   echo $string;
	} else {
	   return $string;
	}
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

96 thoughts on “WooCommerce: Change Add to Cart Quantity into a Select Drop-down

  1. The code works fine on the single product page. I added a function to show the quantity field on the archive page. It works fine without the class “ajax_add_to_cart”. With the class, it doesn’t update the quantity.
    I added the code from here: https://www.businessbloomer.com/woocommerce-ajax-add-to-cart-quantity/

    Any idea? Thanks for your help.

    Kind regards,
    Julia

    1. Hello Julia, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. Hello,

    I tried this code but it doesn’t work unfortunately. My PHP Snippet plugin says:

    The snippet was deactivated due to an error in line number 10:
    Unable to re-declare function woocommerce_quantity_input.

    I’m using Woocoomerce 6.5.0 with Hello theme and Elementor (Pro).

    Kind regards!

    1. You can only redeclare functions via your child theme, and not with a Code Snippets plugin unfortunately

  3. Thanks for this, any way to achieve this design on iOS too? because currently on iOS it looks different.

  4. Hi, I added this piece of code to my functions.php file and I get the listbox in the product page, however the quantity doesn’t carry to the cart page, qty shows as 0 in the cart, although the price seems to be fine.
    I have Avada theme.
    I would like to have a quote to have the list box for quantity fixed, quantity starting with 4, step 4, and adding an option group to the product page.
    Thanks,

    1. Hi Onaida thanks so much for your comment! Feel free to contact me here.

  5. I take back what I just said. I added it to the functions.php file of the child theme and it works great with Hello theme single product page, but doesn’t auto update the cart on quantity change like before.

    1. Hi Colin, thanks so much for your comment! Yes, this is definitely fixable, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

      1. hi, i am not a tech bee but trying to build a site on my own. can you please let me know how i can start the dropdown with 0 as a value in the dropdown.

        1. You’ll need to change several variables in that snippet to 0, sorry I can’t help you more than this

  6. Hi there, I left a comment yesterday reporting that I was getting the “Cannot redeclare woocommerce_quantity_input()” but have since worked out if I enter the php into functions.php in the child theme rather than use the snippet plugin, it works as expected – thank you!

    Just wondering, how would you go about including the static text “Qty” inside the field? Trying to achieve this design > https://www.loom.com/i/5c38a8e961764807b22735781c0ff594

    thanks!

  7. Rodolfo you are the Best thanks a lot !!
    I go to your Business Bloomer Club to thank you !

  8. Any chance you can edit the code snippet, so the drop down is only shown on product pages?

    The default quanity box works great on mobile cart / checkout layouts. A dropdown is too space consuming on cart and checkout pages.

    A tiny change, that would make a great difference.

    1. Hi Kenny! I suggest you take a look at “conditional logic”: https://businessbloomer.com/woocommerce-conditional-logic-ultimate-php-guide/. Enjoy ๐Ÿ™‚

  9. Thank you very much, pal! Works fantastic, but one thing ๐Ÿ™‚

    I added max. to 30. but in the dropdown menu it shows my complete stock.

    I’m on WP Version 5.6.1

    1. How did you add “max”?

  10. We’re using a custom quantity plugin so don’t think this snippet will work for us.
    For example, one of the products has a starting quantity of 0.5 (half a carton) and other custom amounts.

    Got any other ideas please?

    Or just hide the + – with CSS?

    1. Hello Aunty, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  11. Excellent work! I am using a quantity field in the way that woocommerce suggested – using the persons field. How can I get that to be a drop down instead of an input box?

    1. Hey TJ, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  12. I am using flatsome theme and I get “Cannot redeclare function woocommerce_quantity_input” as error. Will it work on flatsome theme

    1. Probably it won’t and may need a workaround

  13. Hi Rodolfo, great piece of code thanks!
    FYI, just want to let you know that this isn’t working with Stripe’s Payment Request Button (Google Pay, Apple Pay, etc.)

    1. Hi Andrea, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  14. In the woocommerce add-product page in WordPress backend, I want to show a dropdown option by replacing the default field (type=’number’). So when I try to add a new product I will no need to input the product stock number rather I will get a pre-build dropdown option such as 122, 222, 333 etc…

    1. Arif, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  15. Cannot redeclare function woocommerce_quantity_input.

    Not working with woocommerce 4.0 now?

    thanks

    1. Works on Storefront theme. Can you temporarily switch to verify that?

  16. great job Sir! thanks a lot!

    1. Thank you!

  17. Hello!
    Like always you made an awesome job…

    How can I add suffix or prefix in the dropbox with the number of order and limite the number ofr order? example “1 for $19,90”, “2 for $37,90”, “3 for $ 49,90”.

    Thank you very much Rodolpho.

    1. Hi Nathalia, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  18. Hi thank you for this great code.
    This is working perfect on the detail page. But in my case i also need this functionality on the shop page. The dropdown is visible as it should, but it only adds 1 item to my basket when i select 2 or more. Is there a way to make this work on my shop page?

    1. Hello Robbert, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  19. I added to this as with variable products I wanted the max qty to be the total amount of the variable quantities so they can’t select a larger amount of what’s available but adding this at the top somewhere

    if(is_singular('product')){
        $variations = $product->get_available_variations();
        foreach($variations as $variation){
            $variation_id = $variation['variation_id'];
            $variation_obj = new WC_Product_variation($variation_id);
            $stockarray[] = $variation_obj->get_stock_quantity();
       }
       $qty = $stockarray;
       $maxqty = array_sum($qty); }
    

    and then changing max quanity from 20 to

    $maxqty

    I need to fine tune this for only variable products, easy with another if statement but just haven’t gotten there yet

    1. Nice!

  20. The code snippet you are trying to save produced a fatal error on line 59:

    Cannot redeclare woocommerce_quantity_input() (previously declared in /home/302087.cloudwaysapps.com/ekquhwjtgj/public_html/wp-content/plugins/woocommerce/includes/wc-template-functions.php:1664)

    Doesn’t work, I’m no programmer.

    1. Are you using a child theme and did you place this in its functions.php file?

      1. I got this same error but I didn’t put it in my functions.php child theme file. Instead, I tried to run it as a plugin so I can activate it from my admin panel.

        1. Try to disable all plugins but Woo and switch theme temporarily – let me know if you still get the error

  21. Thanks for sharing this. Exactly what I needed. Though Iโ€™m curious about the if statement for applying the “selected” attribute. You test if the input_value is greater than 1. But this fails for me when input_value is actually equal to 1 (the most common quantity of a product added to the cart). Thus, when no “selected” attribute is present in html, the dropdown defaults to the first option value, which is often 0.

    A simple change in the if statement greater than comparison to 0 instead of 1 works for me, and correctly applies the “selected” attribute when the quantity is 1.

        if ( '' !== $args['input_value'] && $args['input_value'] > 0 && $count == $args['input_value'] ) {
          $selected = ' selected';
        } else $selected = '';
    

    Alternatively, you could use the greater than or equal to comparison, and keep the value 1. But either one of these changes correctly catches the case where the input_value is 1. Hope that’s helpful.

    1. Excellent thank you!

    2. thank you I had this exact same problem. It needs to be updated in the tutorial

  22. Snippet is not working anymore. There are no options, only empty selection field.

    1. Vaida, thanks for your comment! I just tested this again with Storefront theme and it works perfectly. Maybe your theme (or another plugin) is messing/conflicting with my snippet?

      To troubleshoot, disable all plugins but WooCommerce and also switch temporarily to “Twentyseventeen” theme (load the snippet there in functions.php) – does it work? If yes, you have a problem with your current theme or one of the plugins.

      Hope this helps!

      R

      1. Yep not working for me either.

        Fresh twenty twelve all plugins disabled – except WooCommerce..

        1. Sorry I just did the famous “it’s not working”… I’m getting a with no options..

          1. Snippet revised ๐Ÿ™‚

  23. This is a great feature! I pasted the code in, but there is nothing in the dropdown menu to select. I’m not very familiar with coding, so if I’m missing something obvious please let me know. Thanks!

    1. Hey Joel, it seems this snippet break my single product page and cart page if I use the latest WP/WC versions – please let me know if that’s what you meant

  24. Hi,

    Is it possible to use this tweak only for a selected id of qty selector ?

    Great and thx for your work !

    1. Hi Adrien, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  25. How can we make it work for grouped products?

    1. Hey there, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  26. Hello,

    On my cart page the quantity of products is not changing the quantity

    1. You’re right Caio, try this new version ๐Ÿ™‚

  27. i tried your snippet however in cart page when changing the product quantity then i click the update button it will not update the qty of the product? is their any fix for this? i am running woo 3.5.3. my theme used ajax in changing qty. PLEASE HELP…

    Thanks.

    1. Hey Alvin, this might not be compatible with your theme. Sorry ๐Ÿ˜‰

      1. Alvin, you were right – try this new version ๐Ÿ™‚

  28. This doesn’y work on grouped products. This input name would have to incorporate the product id like so: name=”quantity[” . $product->id . “]”. I tried this but it adds the wrong quantities to the cart and makes the cart page quantity inputs behave improperly.

    1. Geoff, thanks for your comment. You’re surely right, I tested this only with simple products I’m afraid ๐Ÿ™‚

  29. Hi.

    I’m very happy with this code thank you very much for that.

    How can i make the quantity button a bit bigger?

    https://ibb.co/m9Dgh1V

    Thanks.

    1. Hey Asaf, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom CSS work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  30. I have to say, as Aman said above, this code is completely worthless, as it does not work on the cart page and only on a product page. Aman was nice enough to use the word impractical.

    In fact, leaving this code up on the internet does a disservice to the greater WordPress community. If you are not willing to take the time to get it right, please don’t post it in general. This post should be taken down.

    – Tim

    1. Tim, thanks so much for your comment. I felt like publishing it as you’re possibly part of that 0.01% that believes this article does a disservice – that’s fine with me of course ๐Ÿ™‚ Thanks again

      1. Snippet corrected – you were right ๐Ÿ™‚ Let me know!

  31. I am trying to add the Quantity in Drop Down Menu snippet but am receiving this error:

    Don’t Panic

    The code snippet you are trying to save produced a fatal error on line 21:

    “Cannot redeclare woocommerce_quantity_input() (previously declared in /var/www/west-coast-pretzels/wp-content/plugins/woocommerce/includes/wc-template-functions.php:1253)
    The previous version of the snippet is unchanged, and the rest of this site should be functioning normally as before.”

    1. Hey Kevin, thanks for your comment! I think someone was having this same problem, scroll through the previous comment and see if there is a fix ๐Ÿ™‚

    2. may be just change in snippet the div tag to a span tag!

      div tag will “fill” the whole line …

      check it with browser debugger

  32. Its work like a charm, but unlucky there is a problem, the “add to cart” button moved to below quantity selector. any one can help me how to move back the “add to cart” button next to quantity selector again?

    1. Hey Anam, thanks so much for your comment! You will need some custom, simple CSS there so I’m afraid I can’t help here ๐Ÿ™‚

  33. Thank you for the starting point, i use your info a lot! For anyone who is interested there is also this option I have put together here.

    https://gist.github.com/splozm/a73d19659dd11e26fcae67d74ae0ba4c

    It accurately reflects the quantity a user has selected and displays with a drop down in the basket.

    1. Thanks Alex ๐Ÿ™‚

  34. This snippet works great to change the qty selector to drop down. It also helps to style qty drop down. However, unfortunately, the quantities in the cart are not calculated accurately in the cart. These issues make this snippet rather impractical in its current form.

    Still, many thanks Rodolfo for your work.

    1. Hey Matt, thanks for your comment ๐Ÿ™‚ I just retested this and it correctly adds to cart from the single product page (haven’t tested other scenarios). The problem appears in the Cart, where the quantities are back to 1 despite the price is correctly calculated… Ok, a little buggy, I will see if I can fix this soon ๐Ÿ™‚

      1. This is a first attempt that only works on the single product page – still needs lots of work though:

        
        add_action( 'wp_footer', 'bbloomer_update_qty' ); 
         
        function bbloomer_update_qty() { 
            if ( is_product() ) { 
                ?> 
                <script type="text/javascript"> 
        			jQuery('input.qty').replaceWith('<select name="quantity">' +
        			'<option value="1">1</option>' +
        			'<option value="2">2</option>' +
        			'<option value="3">3</option>' +
        			'<option value="4">4</option>' +
        			'<option value="5">5</option>' +
        			'</select>'); 
                </script> 
                <?php 
            } 
        }
        
        
  35. Hi Rodolfo,
    Thank you for great tutorials, They are helping us a lot. I have interesting task which i am struggling to get around. for above quantity drop down, is there any possibility to add more option as a last option. people choose predefined quantities from drop down and if someone want to enter quantity which is not in the list, they will click on more and as soon as they click on more quantity input text box will be open then customer can enter their desired quantity. It would be great if you could help me with it.

    1. Hello Sunny, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  36. Hi
    I have just added it. But in the cart page the value that is set in drop down is not remaining selected. Once I select it and hit update cart button then it revers back to 1 and the total is not also updated. Any idea about this ?

    1. Aman, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom troubleshooting work and I cannot provide a solution here via the blog comments. Thanks a lot for your understanding! ~R

    2. 
      function woocommerce_quantity_input($data = null,$product)
      {
          global $post;
          if ( is_null( $product ) ) {
              $product = $GLOBALS['product'];
          }
        
          if (!$data['input_name']) {
              $defaults = array(
                  'input_name' =&gt; 'quantity',
                  'input_value' =&gt; 100,
                  'max_value' =&gt; apply_filters('woocommerce_quantity_input_max', '10000', $product),
                  'min_value' =&gt; apply_filters('woocommerce_quantity_input_min', '50', $product),
                  'step' =&gt; apply_filters('woocommerce_quantity_input_step', '100', $product),
                  'style' =&gt; apply_filters('woocommerce_quantity_style', 'float:left;margin-right:10px;', $product)
              );
          } else {
              $defaults = array(
                  'input_name' =&gt; $data['input_name'],
                  'input_value' =&gt; $data['input_value'],
                  'step' =&gt; apply_filters('cw_woocommerce_quantity_input_step', '100', $product),
                  'max_value' =&gt; apply_filters('cw_woocommerce_quantity_input_max', '10000', $product),
                  'min_value' =&gt; apply_filters('cw_woocommerce_quantity_input_min', '100', $product),
                  'style' =&gt; apply_filters('cw_woocommerce_quantity_style', 'float:left;margin-right:10px;', $product)
              );
          }
      
          $options = '';
      
          $quantities = array(100, 250, 500, 1000, 2000, 4000, 6000, 8000, 10000);
      
          if (!in_array($defaults['input_value'],$quantities))
              $quantities[] = $defaults['input_value'];
      
          asort($quantities);
      
          foreach ($quantities as $qty) {
              $selected = $qty === $defaults['input_value'] ? ' selected' : '';
      
              $options .= '' . $qty . '';
      
          }
          echo '' . $options . '';
      }
      
      
    3. I have the same problem!

  37. Thanks

  38. Hey i nice idea indeed!
    But I’m here to report and error unfortunately:
    “The code snippet you are trying to save produced a fatal error on line 21:

    Cannot redeclare woocommerce_quantity_input() (previously declared in /data/vhosts/oramonline.it/httpdocs/woodef/wp-content/plugins/woocommerce/includes/wc-template-functions.php:1080)”

    The line 21 is: “}”

    1. Hey Paolo, thanks for your comment! You should place my snippet in the functions.php of your child theme, not via a third party code snippet plugin. Let me know ๐Ÿ™‚

  39. Awesome one, Worked like charm. . thanks

  40. Thanks for the snippets Rodolfo! Your snippets have helped me out numerous times when I have needed to customize WooCommerce for my clients.

    Cheers,
    Shaun.

  41. I like the idea of a pluggable function, but it seems like you need to use it in functions.php and not in a custom plugin. As I understand it, if you use it in a plugin there is a chance your plugin will load before Woocommerce and the WC function will take precedence. Or does WC have an if-exists test in its declaration?

    1. Hey Peter, thanks for your comment! It’s highly recommended to use child themes and not code snippet plugins – in there everything should work and load correctly ๐Ÿ™‚

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *