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.

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

/**
 * @snippet       Add to Cart Quantity drop-down - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 5.0
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
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( 'input-text', '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"><span>Qty</span><select name="' . $args['input_name'] . '">' . $options . '</select></div>';

	if ( $echo ) {
	   echo $string;
	} else {
	   return $string;
	}
 
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

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

  1. 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

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

  3. 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.

  4. 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

  5. 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!

  6. Rodolfo you are the Best thanks a lot !!
    I go to your Bloomer Armada to thank you !

  7. 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 πŸ™‚

  8. 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”?

  9. 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!

  10. 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!

  11. 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

  12. 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!

  13. 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!

  14. 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?

  15. great job Sir! thanks a lot!

    1. Thank you!

  16. 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!

  17. 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!

  18. 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!

  19. 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

  20. 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

  21. 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 πŸ™‚

  22. 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

  23. 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

  24. 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

  25. Hello,

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

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

  26. 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 πŸ™‚

  27. 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 πŸ™‚

  28. 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

  29. 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!

  30. 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

  31. 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 πŸ™‚

  32. 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.

  33. 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 
            } 
        }
        
        
  34. 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

  35. 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!

  36. Thanks

  37. 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 πŸ™‚

  38. Awesome one, Worked like charm. . thanks

  39. 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.

  40. 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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.