56293

Make checkout phone field optional for specific countries in WooCommerce

Question:

I have to display phone as required (mandatory) only if a certain country is selected in WooCommerce checkout screen.

What is the validation rule to check the selected country in real time?

I have tried the following code, which is working for making phone non required:

add_filter( 'woocommerce_billing_fields', 'wc_npr_filter_phone', 10, 1 ); function wc_npr_filter_phone( $address_fields ) { $address_fields['billing_phone']['required'] = false; return $address_fields; }

Answer1:

You mostly need to use javascript for real time events or live events on client side… The code below is mostly using jQuery and a bit of PHP, to make the billing phone required only when customer select specific countries:

// Making the billing phone field not required (by default) add_filter( 'woocommerce_billing_fields', 'filter_billing_phone_field', 10, 1 ); function filter_billing_phone_field( $fields ) { $fields['billing_phone']['required'] = false; return $fields; } // Real time country selection actions add_action( 'woocommerce_after_order_notes', 'custom_checkout_scripts_and_fields', 10, 1 ); function custom_checkout_scripts_and_fields( $checkout ) { $required = esc_attr__( 'required', 'woocommerce' ); // HERE set the countries codes (2 capital letters) in this array: $countries = array( 'UK', 'BE', 'GE', 'IT', 'ES' ); // Hidden field for the phone number validation echo '<input type="hidden" name="billing_phone_check" id="billing_phone_check" value="0">'; $countries_str = "'".implode( "', '", $countries )."'"; // Formatting countries for jQuery ?> <script type="text/javascript"> (function($){ var required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>', countries = [<?php echo $countries_str; ?>], location = $('#billing_country option:selected').val(), phoneCheck = 'input#billing_phone_check'; function actionRequire( actionToDo='yes', selector='' ){ if ( actionToDo == 'yes' ) { $(selector).addClass("validate-required"); $(selector+' label').append(required); } else { $(selector).removeClass("validate-required"); $(selector+' label > .required').remove(); } $(selector).removeClass("woocommerce-validated"); $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field"); } // Default value when loading actionRequire( 'no','#billing_phone_field' ); if( $.inArray( location, countries ) >= 0 && $(phoneCheck).val() == '0' ){ actionRequire( 'yes','#billing_phone_field' ); $(phoneCheck).val('1'); } // Live value $( 'form.checkout' ).on( 'change', '#billing_country', function(){ var location = $('#billing_country option:selected').val(); if ( $.inArray( location, countries ) >= 0 && $(phoneCheck).val() == 0 ) { actionRequire( 'yes','#billing_phone_field' ); $(phoneCheck).val('1'); } else if ( $(phoneCheck).val() == 1 ) { actionRequire( 'no','#billing_phone_field' ); $(phoneCheck).val('0'); } }); })(jQuery); </script> <?php } // Phone number validation, when it's visible add_action('woocommerce_checkout_process', 'billing_phone_field_process'); function billing_phone_field_process() { // Check if set, if its not set add an error. if ( ! $_POST['billing_phone'] && $_POST['billing_phone_check'] == '1' ) wc_add_notice( __( 'Please enter a number phone.' ), 'error' ); }

<em>Code goes in function.php file of your active child theme (or theme) or also in any plugin file.</em>

Tested and works.

<blockquote>

Related (2019): <a href="https://stackoverflow.com/questions/55206672/make-woocommerce-checkout-phone-field-optional-based-on-shipping-country/55209546#55209546" rel="nofollow">Make Woocommerce checkout phone field optional based on shipping country</a>

</blockquote>

Recommend

  • How to redirect command prompt output to a file using asp.net C#?
  • Enabling and disabling keyboard input using jquery
  • Pathfinding in 2D Arrays
  • Draw a curve (bezier curve) between two lat long points on google maps android
  • How to create an empty list in Dart
  • Compatibility Mode in IE8 using VBScript
  • boost to_upper function of string_algo doesn't take into account the locale
  • Numpy array to TFrecord
  • How to turn off Pydev indentation warnings for certain .py files
  • Jquery element.text() error “is not a function” when I use elements array
  • File moving according to substring derived from file name
  • Is there a way to suppress MOTD when starting up R?
  • C format issue with printf(“%d”, astatbuff->st_size); [duplicate]
  • Qt: How to set header on child tables in QAbstractItemModel?
  • Optional or conditional folders in NuGet files tag?
  • How to build an embedding layer in Tensorflow RNN?
  • Delphi MainFormOnTaskBar Modal windows bug
  • Adding a delete button in PHP on each row of a MySQL table
  • Automate editable PDF
  • How to implement tap to focus on barcode scanner app using swift?
  • typescript multidimensional array with different types
  • Highcharts Drawing a line with chart.renderer.path
  • PHP users local time
  • Dynamic reference casting depending on actual object type
  • Whatsapp Image sharing not working
  • Bulk loading into PostgreSQL from a remote client
  • Git for windows has stopped working
  • SqlDatasource select parameters
  • Align microsoft access queries
  • Convert current tmux session to configuration file
  • SpringBoot don't replacen System variable {user.home} in Spring Tool Suite Version: 3.8.4.RELEA
  • Example of using Service Exists MSBuild task in Microsoft.Sdc.Tasks?
  • How do I set the logging properties in a spring java configuration?
  • How does the dispatcher work when mixing sync/async with serial/concurrent queue?
  • Modifying native query cannot have named parameter bindings?
  • Adding native code to an existing Worklight hybrid app
  • Allowing audio files in Spring MVC 3.0?
  • Swift manually rotate view controller
  • java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/SpringDispatcher-ser
  • How to warp text around image in iOS?