Plus and Minus Buttons on Quantity Fields
Adds "-" and "+" buttons around the quantity box on product and cart pages so shoppers can change quantities with a tap.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! function_exists( 'is_woocommerce' ) || ! ( is_product() || is_cart() ) ) {
return;
}
?>
<style>
.wpide-qty-wrap{display:inline-flex;align-items:stretch;}
.wpide-qty-wrap .qty{text-align:center;-moz-appearance:textfield;}
.wpide-qty-wrap .qty::-webkit-inner-spin-button,.wpide-qty-wrap .qty::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}
.wpide-qty-btn{min-width:36px;border:1px solid #ccc;background:#f6f7f7;cursor:pointer;font-size:18px;line-height:1;}
</style>
<script>
(function () {
function enhance(root) {
root.querySelectorAll('.quantity input.qty:not([data-wpide-qty]):not([type="hidden"])').forEach(function (input) {
input.setAttribute('data-wpide-qty', '1');
var wrap = document.createElement('span');
wrap.className = 'wpide-qty-wrap';
input.parentNode.insertBefore(wrap, input);
['-', '+'].forEach(function (sign) {
var b = document.createElement('button');
b.type = 'button';
b.className = 'wpide-qty-btn';
b.textContent = sign;
b.setAttribute('aria-label', sign === '+' ? 'Increase quantity' : 'Decrease quantity');
b.addEventListener('click', function () {
var step = parseFloat(input.step) || 1, min = parseFloat(input.min) || 0, max = parseFloat(input.max), val = parseFloat(input.value) || 0;
val = sign === '+' ? val + step : val - step;
if (val < min) { val = min; }
if (!isNaN(max) && max > 0 && val > max) { val = max; }
input.value = val;
input.dispatchEvent(new Event('change', { bubbles: true }));
});
if (sign === '-') { wrap.appendChild(b); wrap.appendChild(input); } else { wrap.appendChild(b); }
});
});
}
enhance(document);
if (window.jQuery) { jQuery(document.body).on('updated_cart_totals', function () { enhance(document); }); }
})();
</script>
<?php
} );
Notes
The buttons respect the minimum, maximum and step values of the quantity field.
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.