WooCommerce: Checkbox to Hide/Show Custom Checkout Field

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.

BEFORE: new checkout checkbox is not checked – therefore the new field shows
AFTER: new checkout checkbox is checked – therefore the new field disappears

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 CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WC 4.1
 * @community     https://businessbloomer.com/club/
 */
 
add_filter( 'woocommerce_checkout_fields' , 'bbloomer_display_checkbox_and_new_checkout_field' );
 
function bbloomer_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', 'bbloomer_conditionally_hide_show_new_field', 9999 );
 
function bbloomer_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();
  ");
      
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Disable Payment Method If Product Category @ Cart
    Today we take a look at the WooCommerce Checkout and specifically at how to disable a payment gateway (e.g. PayPal) if a specific product category is in the Cart. There are two tasks to code in this case: (1) based on all the products in the Cart, calculate the list of product categories in the […]
  • WooCommerce: Add Privacy Policy Checkbox @ Checkout
    Here’s a snippet regarding the checkout page. If you’ve been affected by GDPR, you will know you now need users to give you Privacy Policy consent. Or, you might need customer to acknowledge special shipping requirements for example. So, how do we display an additional tick box on the Checkout page (together with the existing […]
  • WooCommerce: Redirect to Custom Thank you Page
    How can you redirect customers to a beautifully looking, custom, thank you page? Thankfully you can add some PHP code to your functions.php or install a simple plugin and define a redirect to a custom WordPress page (as opposed to the default order-received endpoint). This is a great way for you to add specific up-sells, […]
  • WooCommerce: Disable Payment Gateway by Country
    You might want to disable PayPal for non-local customers or enable a specific gateway for only one country… Either way, this is a very common requirement for all of those who trade internationally. Here’s a simple snippet you can further customize to achieve your objective. Simply pick the payment gateway “slug” you want to disable/enable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

48 thoughts on “WooCommerce: Checkbox to Hide/Show Custom Checkout Field

  1. Hey Rodolfo, this is a great snippet.
    Thanks a lot!

  2. Hi Rodolfo!
    I’m using your code with a required field. When it’s not showing, WooCommerce still ask the user to complete it.

    How to hide the field and also remove the “required”?

    Thanks!

    1. Ciao Luca, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  3. Hello there,

    First of all, thank you very much.

    How can I see the note written on the order edit page

    1. Hi there, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  4. Hello Rodolfo.

    Using your instructions I created a modified code to hide and display the Billing Details using a checkbox.

    By default I have set so that the Billing Details are hidden.
    The user can display them just by checking the Checkbox.

    However, when a validation error occurs in the fields, such as the failure to fill in a mandatory field, the user receives the error message, but as the fields are hidden he may have difficulty locating the field, as he would have to check the checkbox to be able to see all the fields.

    I’m trying, unsuccessfully, to have the checkbox automatically checked when an error occurs on this checkout page, but I’m not getting it.

    Can you take a look at the code below?

    Can you help-me with this?

    1. Guilherme, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  5. hello @Rodolfo Melogli thank you for nice instruction how to add additional field based on checkbox(check/not).. i checked this code and get an error .. actually this field value doesn’t appear into order details page … i mean once i booked any order i could not see what customer typed into this field …can you kindly help me how can i show this field data into admin dashboard …Thanks in advance

    1. Hi Saifur, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  6. Rodolfo non so come ringraziarti…i tuoi insegnamenti sono i migliori del web…ti ringrazierรฒ sicuramente nei credits del mio ecommerce e del mio plugin, e la mia donazione la meriti davvero tutta.

    1. Thank you / Grazie!

  7. Hiya, Iโ€™m unable to add This multiple times for multiple fields/boxes. Why is this?

    1. Hi Elly, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  8. Hi,

    Great approach, but it does the exact opposite as what you describe on top of the page:
    ” if the checkbox is ticked, the field will show, otherwise it will disappear again.”.
    What it actually does, is hide a field on ticking on the checkbox (fadeOut), or show it when unticked.

    I reversed the fadeIn with fadeOut, but then on pageload it gives a buggy result:
    Showing the field at first, then disappearing.

    I do assume you meant to make it work, like the default WC field ‘Create an account?’ works, right?
    Else I cannot come up with any practical usecase for this.

    Can you revise the code perhaps?
    (this way it looks like clickbait in the description, surely that was not the purpose of this great snippet).

    1. I wouldn’t call it clickbait. Anyway, just use “!this.checked” instead of “this.checked” and it’ll work the way you want. Cheers

      1. Hi,

        Thanks for sharing!
        as No said, actually with “!this.checked” works, but when page loads you can see the field also if the checkbox it’s empty.
        Therefore it still miss something to work as said..
        Cheers

        1. Sure. Just before:

             jQuery('input#checkbox_trigger').change(function(){
          

          write:

             jQuery('#new_billing_field_field').fadeOut();
             jQuery('input#checkbox_trigger').change(function(){
          
          1. so thanks for this help

            1. You’re welcome!

  9. Hi, I have problem with label , why label is not hide with all field? No matters that checkbox is mark or no, label is always shows.

    1. What’s the code you used exactly?

      1. Yes, I have the same issue here. Used the original code.

        1. If you used the exact same code, “new_billing_field_field” targets label + input so that’s weird. Maybe you need to adjust the JS according to your custom HTML

  10. How to add multiple fields to show after check?
    $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
    );
    here..

    1. Just add another $fields[][] block

      1. Adding a new field block doesn’t work

        1. Share your full code please?

  11. Thank you Rodolfo.
    This is exactly what I was looking for.

    1. Excellent

  12. Hi Rodolfo,

    Thank you for this snippet.

    I have customised it to show only on click

    Do you have any tips to make it show/hide the company name field based on the checkbox status? So basically change the following to show the already available company field

    $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
    ); 
    1. Hi Ioannis, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  13. Hi rodolfo, i’m trying to modify your snippet but i have no success.:(

    1) i created a new field “cf_field”
    2) if #billing_country value is different from ‘IT’ i want to hide dinamically

     
    
    function bbloomer_display_and_hide_a_field( $fields ) {
     
    $fields['billing']['cf_field'] =
                               array(
                                    'type'          => 'text',
                                    'class'         => array('cf-class form-row-wide'),
                                    'label'         => __('Codice fiscale'),
                                    'placeholder'   => __('Insert your cf'),
                                    'required'  => true, 
                                    'clear'     => true,
                                    );
                              
    return $fields;
     
    }
    
    add_action( 'woocommerce_after_checkout_form', 'bbloomer_conditionally_hide_show_a_field', 6);
     
    function bbloomer_conditionally_hide_show_a_field() {
       
      ?>
        <script type="text/javascript">
            jQuery('input#cf_field').change(function(){ ---> incorrect
                 
                if (jQuery('#billing_country').val() != 'IT'){
                jQuery('#cf_field').fadeOut();
                }
    		 }
                 
            });
        </script>
        <?php
           
    }
    ?>
    
    1. Marco, thanks so much for your comment! Unfortunately this looks like custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  14. Hi, how can i move the new checkbox on the top ?

    Thank u so mutch.

    1. Ciao Daniele, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  15. Hello Rodolfo,

    First of all thanks for this snippet. I want to move the checkbox to hook “woocommerce_before_checkout_billing_form”, but somehow the checkbox does not move to the required hook? Is this possible?

    TYhanks,
    Tim

    1. Tim, thanks so much for your comment! Unfortunately this looks like custom troubleshooting work and I cannot help here via the blog comments. Thanks a lot for your understanding! ~R

  16. Hi, thank you! I try to work with this all day but I does not work the way I want. Its posible to contact you? Regards, Jordi

    1. Jordin, if you’d like to get a quote, feel free to contact me here. Thanks a lot

  17. Hi! Great snippet, I’ve been trying to solve this problem for weeks. However, I need to modify it a bit and I’m having a hard time doing so. I need it to work this way – in the default situation the field won’t show at all, only the checkbox. When checkbox is checked, the field appears. Also, the input is not showing in the administration. Is there any way to fix this? Thanks a lot! ๐Ÿ™‚

    1. Michal, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here on the blog. Thanks a lot for your understanding! ~R

  18. Hi, i want to add a checkbox if a customer rewuires invoice. In that case (if it is checked by the customer) company field, profession field (a custom field) and vat field (already added by a vat plugin at checkout fields) would have to appear and be required. Can this be done with your code?

    1. Hey Akis thanks for your comment! Yes, you will need to modify it, but my snippet shows you how to achieve what you need ๐Ÿ™‚

  19. Hi Rodolfo, this is a great snippet. But if the initially hidden field would be required, I’d still get required field message. Is there a solution for a scenario with a required field?

    1. Hey Rasti! If the field is required, why do you need to hide it?

    2. Hi, its possible to start this hide, so not show the new field. Just when you check the new field will show. Thank you! I really need this function for my website. Regards.

      1. Hey Jordi, thanks for your comment! Yes, of course, this is possible, you just need to customize my snippet. Sorry but I can’t help with custom work here via the blog comments. Thank you ๐Ÿ™‚

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *