WooCommerce: Change Add to Cart “Quantity” into a 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        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=72757
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.5.4
 * @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',
   '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' : '' ),
);

$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 );
$args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';

// 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 (before "?>" if you have it). 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+.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce Customization?

Check out these free video tutorials!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP

Rodolfo Melogli

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as a 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.

47 thoughts on “WooCommerce: Change Add to Cart “Quantity” into a Drop-down

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

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

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

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

  5. Hello,

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

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

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

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

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

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

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

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

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

  13. 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 
            } 
        }
        
        
  14. 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

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

  16. Thanks

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

  18. Awesome one, Worked like charm. . thanks

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

  20. 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: [php]code_here[/php]. Failure to complying with this (as well as going off topic) will result in comment deletion. You should expect a reply in about a week - this is a popular blog but I need to get paid work done first. Please consider joining #BloomerArmada to ask me 1-to-1 WooCommerce questions. Thank you :)

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.