Quantity Dropdown Instead of a Number Box
Replaces the quantity number box with a simple dropdown (1, 2, 3...) on product and cart pages, which is faster to use on phones.
Opens WPIDE on
Code
$wpide_qty_options = 20; // Highest option when the product has no maximum.
add_action( 'wp_footer', function () use ( $wpide_qty_options ) {
if ( ! function_exists( 'is_product' ) || ! ( is_product() || is_cart() ) ) {
return;
}
?>
<script>
( function () {
var cap = <?php echo (int) $wpide_qty_options; ?>;
function convert( root ) {
root.querySelectorAll( 'input.qty[type="number"]:not([data-wpide])' ).forEach( function ( input ) {
var min = parseFloat( input.min ) || 1, step = parseFloat( input.step ) || 1;
var max = parseFloat( input.max ) || 0;
if ( input.type === 'hidden' || ( max && max <= min ) ) { return; }
var limit = max ? Math.min( max, min + step * ( cap - 1 ) ) : min + step * ( cap - 1 );
var current = parseFloat( input.value ) || min;
var select = document.createElement( 'select' );
select.name = input.name;
select.id = input.id;
select.className = input.className;
select.setAttribute( 'aria-label', input.getAttribute( 'aria-label' ) || 'Quantity' );
for ( var q = min; q <= limit; q += step ) { select.add( new Option( q, q, false, q === current ) ); }
if ( current > limit ) { select.add( new Option( current, current, true, true ) ); }
input.setAttribute( 'data-wpide', '1' );
select.addEventListener( 'change', function () { select.dispatchEvent( new Event( 'input', { bubbles: true } ) ); } );
input.parentNode.replaceChild( select, input );
} );
}
convert( document );
if ( window.jQuery ) { jQuery( document.body ).on( 'updated_cart_totals', function () { convert( document ); } ); }
} )();
</script>
<?php
} );
Notes
Respects each product's minimum, maximum and step, offering up to $wpide_qty_options choices when there is no maximum.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.