1

I saw this question come up before but it was answered reversely. I would like question answered exactly as asked. I would like the phone number field to change from required to optional if a country is chosen. I currently have the phone number field is required for all countries. I would like that if United States is chosen then phone number should be change to optional.
For reference, here is original post
https://stackoverflow.com/questions/55206672/make-woocommerce-checkout-phone-field-optional-based-on-shipping-country and below is the code to have list of countries changed to required.

// SETTINGS: The countries codes (2 capital letters) in the array
function defined_countries_for_phone_field(){
    return array( 'GB', 'JE', 'GG', 'IM' );
}

// Remove "(optional)" from non required "Billing phone" field
add_filter( 'woocommerce_form_field' , 'remove_checkout_optional_fields_label', 10, 4 );
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {

    // Get the defined countries codes
    $countries = defined_countries_for_phone_field();

    // Get Customer shipping country
    $shipping_country = WC()->customer->get_shipping_country();

    // Only on checkout page and My account > Edit address for billing phone field
    if( 'billing_phone' === $key && ( ( is_wc_endpoint_url( 'edit-address' )
    && in_array($shipping_country, $countries) ) || is_checkout() ) ) {
        $optional = '&nbsp;<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $field = str_replace( $optional, '', $field );
    }
    return $field;
}

// Make the billing phone field optional (by default)
add_filter( 'woocommerce_billing_fields', 'filter_billing_phone_field', 10, 1 );
function filter_billing_phone_field( $fields ) {

    // Get the defined countries codes
    $countries = defined_countries_for_phone_field();

    // Get Customer shipping country
    $shipping_country = WC()->customer->get_shipping_country();

    // Only on checkout page and My account > Edit address
    if ( ( is_wc_endpoint_url( 'edit-address' )
    && in_array($shipping_country, $countries) ) || is_checkout() )
        $fields['billing_phone']['required'] = false;

    return $fields;
}

// Real time shipping 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' );

    // Get the defined countries codes
    $countries = defined_countries_for_phone_field();

    // 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>';
            var countries = [<?php echo $countries_str; ?>];
                if($('.shipping_address').is(':visible')) {
                    // ship to different country selected
                    var selectedcountry = $('#shipping_country option:selected').val();
                } else {
                    var selectedcountry = $('#billing_country option:selected').val();
                }
             //var selectedcountry = $('#shipping_country option:selected').val();
             var phoneCheck = 'input#billing_phone_check';
             var phoneField = '#billing_phone_field';

            function actionRequire( actionToDo='yes', selector='' ){
                if ( actionToDo == 'yes' ) {
                    $(selector).addClass("validate-required");
                    $(selector+' label > .required').remove();
                    $(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 Once DOM is loaded (with a 300 ms delay)
            setTimeout( function(){
                if($('.shipping_address').is(':visible')) {
                    // ship to different country selected
                    var selectedcountry = $('#shipping_country option:selected').val();
                } else {
                    var selectedcountry = $('#billing_country option:selected').val();
                }
                actionRequire( 'no', phoneField );
                if( $.inArray( selectedcountry, countries ) == -1){
                    actionRequire( 'yes',phoneField );
                    $(phoneCheck).val('1');
                }
            }, 300 );

            // Live value
            $( 'form.checkout' ).on( 'change', '#billing_country, #shipping_country, #ship-to-different-address-checkbox', function(){
                setTimeout( function(){
                    if($('.shipping_address').is(':visible')) {
                        // ship to different country selected
                        var selectedcountry = $('#shipping_country option:selected').val();
                    } else {
                        var selectedcountry = $('#billing_country option:selected').val();
                    }

                    if ( $.inArray( selectedcountry, countries ) == -1) {
                        actionRequire( 'yes' ,phoneField );
                        $(phoneCheck).val('1');
                    } else {
                        actionRequire( 'no' ,phoneField );
                        $(phoneCheck).val('0');
                    }
                }, 300 );
            });
       })(jQuery);
        </script>
    <?php
}

// Phone number validation, when the field is required
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' );
}
pwidner
  • 11
  • 1
  • What is the issue? – Bhautik Jun 03 '22 at 18:26
  • The issue is the code above makes it required for the countries in the list array. I would like to see code for making phone number optional with list of countries. There are too many countries to list as required but only one country to list as optional. – pwidner Jun 06 '22 at 16:09
  • What have you tried so far? – Bhautik Jun 06 '22 at 18:31

0 Answers0