Make checkout phone field optional for specific countries in WooCommerce

后端 未结 1 2038
我在风中等你
我在风中等你 2021-01-15 19:57

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 selec

1条回答
  •  梦谈多话
    2021-01-15 20:44

    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 '';
        $countries_str = "'".implode( "', '", $countries )."'"; // Formatting countries for jQuery
        ?>
        
        

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

    Tested and works.

    Related (2019): Make Woocommerce checkout phone field optional based on shipping country

    0 讨论(0)
提交回复
热议问题