Last active
August 16, 2024 23:06
-
-
Save purag/8d22e297595e4639552ce3c3b40c9a1a to your computer and use it in GitHub Desktop.
Add plus and minus buttons to WPForms "Single Item" field quantity selector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.