54
This snippet could come really handy for several reasons. When you’ll need to do advanced customization of the checkout and its fields, hopefully you’ll thank me then 🙂
In today’s snippet, we will add a new checkbox and another new “hidden” field – then, if the checkbox is ticked, the field will show, otherwise it will disappear again.
PHP Snippet: Add a Checkbox to Hide/Show a Custom Checkout Field
/**
* @snippet Add a Checkbox to Hide/Show Checkout Field - WooCommerce
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WC 4.1
* @donate $9 https://tutoraspire.com
*/
add_filter( 'woocommerce_checkout_fields' , 'tutoraspire_display_checkbox_and_new_checkout_field' );
function tutoraspire_display_checkbox_and_new_checkout_field( $fields ) {
$fields['billing']['checkbox_trigger'] = array(
'type' => 'checkbox',
'label' => __('Checkbox label', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['new_billing_field'] = array(
'label' => __('New Billing Field Label', 'woocommerce'),
'placeholder' => _x('New Billing Field Placeholder', 'placeholder', 'woocommerce'),
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
add_action( 'woocommerce_after_checkout_form', 'tutoraspire_conditionally_hide_show_new_field', 9999 );
function tutoraspire_conditionally_hide_show_new_field() {
wc_enqueue_js( "
jQuery('input#checkbox_trigger').change(function(){
if (! this.checked) {
// HIDE IF NOT CHECKED
jQuery('#new_billing_field_field').fadeOut();
jQuery('#new_billing_field_field input').val('');
} else {
// SHOW IF CHECKED
jQuery('#new_billing_field_field').fadeIn();
}
}).change();
");
}