Skip to content

Instantly share code, notes, and snippets.

@purag
Last active August 16, 2024 23:06
Show Gist options
  • Save purag/8d22e297595e4639552ce3c3b40c9a1a to your computer and use it in GitHub Desktop.
Save purag/8d22e297595e4639552ce3c3b40c9a1a to your computer and use it in GitHub Desktop.
Add plus and minus buttons to WPForms "Single Item" field quantity selector
<?php
// Insert Plus and Minus buttons on eligible Single Item fields.
function wpforms_maybe_insert_single_item_controls() {
?>
<script type="text/javascript">
const select = document.querySelector('.wpforms-insert-single-item-controls select');
function getSelector(direction) {
return (event) => {
event.preventDefault();
event.stopPropagation();
const min = Number(select[0].value);
const max = Number(select[select.length - 1].value);
jQuery(select)
.val(Math.max(min, Math.min(max, Number(jQuery(select).val()) + direction)))
.trigger('change');
};
}
const minusButton = document.createElement('button');
minusButton.classList.add('wpforms-single-item-control', 'wpforms-single-item-control-minus');
minusButton.textContent = '-';
minusButton.addEventListener('click', getSelector(-1));
select.insertAdjacentElement('beforebegin', minusButton);
const plusButton = document.createElement('button');
plusButton.classList.add('wpforms-single-item-control', 'wpforms-single-item-control-plus');
plusButton.textContent = '+';
plusButton.addEventListener('click', getSelector(1));
select.insertAdjacentElement('afterend', plusButton);
</script>
<?php
}
add_action('wpforms_wp_footer_end', 'wpforms_maybe_insert_single_item_controls', 30);
@purag
Copy link
Author

purag commented Aug 16, 2024

I used WPCode to add this PHP snippet as a shortcode. Then I placed the shortcode on the page with the WPForms form that I wanted to apply this to.

You also need to add wpforms-insert-single-item-controls as a custom class on the field you want it to add the controls to.

Note, as written it will only apply this to the first Single Item field with the custom class applied. The code could be modified to just use querySelectorAll, loop over the results, and apply the treatment to all instances.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment