How to automatically hide WooCommerce checkout field?

You have seen how to hide checkout fields of a virtual product at cart. In this article, you will learn to automatically hide WooCommerce checkout field. It means that you can hide a field if another field does not contain any information or value.

In our example, you will learn to hide the “contact number” if no “company name” is entered. To activate this, you will need to deactivate the attribute for billing phone from WooCommerce customizer settings. If you do not disable it, then checkout validation is going to fail. Apart from this, you can even apply this snippet to other checkout field combos. All you need to do is identify the IDs and alter jQuery based on it. 

Image showing how to automatically hide WooCommerce checkout field

In the example, you will learn how to hide “Phone” field when “Company name” field is empty.

PHP Snippet: Automatically Hide Checkout Field if Another Field is Empty

add_action( 'woocommerce_after_checkout_form', 'phpsof_conditionally_hide_show_checkout_field', 9999 );
  
function phpsof_conditionally_hide_show_checkout_field() {
   wc_enqueue_js( "
      jQuery('#billing_company').keyup(function() {
         if (jQuery(this).val().length == 0) {
            jQuery('#order_comments_field').hide();
         } else {
            jQuery('#order_comments_field').show();
         }
      }).keyup();
   ");
}

Where do you add this snippet?

So, this is how you automatically hide WooCommerce checkout field. Also, it is easier to activate this function with this code. So, to apply this code, just add this PHP snippet at your child theme function.php file’s bottom. It should be placed before “?>”, if you have it there. Apart from this, CSS goes in your child theme style.css file. Make sure that you are editing these files in a right manner for best results.

Is this snippet still valid?

So, this way, you automatically hide WooCommerce checkout fieldI have applied this code on the Storefront theme and WordPress friendly hosting PHP 7.3. Let me know if everything works as expected when you code. Share it further if you find this snippet useful for you and it had saved your time. 

Also Read, How to switch WooCommerce Multiple PayPal Accounts?

How to enable WooCommerce Multiple Stripe Accounts?

Important link: WooCommerce – https://woocommerce.com/