基于发货国家,使WooCommerce结账页面的电话字段变为可选。

4
在Woocommerce结账时,我想让特定运输国家的电话栏位变成非必填项。基于“Make checkout phone field optional for specific countries in WooCommerce”答案中的代码,这个代码可以正常工作,但是我试图对其进行一些更改,使其适用于运输国家而不是账单国家。
尝试了很多次后,我仍然无法弄清楚如何让它工作。
任何帮助都非常感谢。
2个回答

5
以下代码将使账单电话字段仅对特定的“Shipping”国家为必填项。
自WooCommerce 3.4+版本以来,WooCommerce表单字段发生了一些变化,因此需要额外的函数和代码。
我还扩展了代码以处理“我的帐户”>“编辑地址”中的电话字段行为,客户可以更改其帐户数据。
以下是完整的代码(在第一个函数中定义您的国家代码):
// SETTINGS: The countries codes (2 capital letters) in the array
function defined_countries_for_phone_field(){
    return array( 'UK', 'BE', 'GE', 'IT', 'ES' );
}

// 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>',
                countries = [<?php echo $countries_str; ?>],
                location = $('#shipping_country option:selected').val(),
                phoneCheck = 'input#billing_phone_check',
                phoneField = '#billing_phone_field';

            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 Once DOM is loaded (with a 300 ms delay)
            setTimeout( function(){
                actionRequire( 'no', phoneField );
                if( $.inArray( location, countries ) >= 0  && $(phoneCheck).val() == '0' ){
                    actionRequire( 'yes',phoneField );
                    $(phoneCheck).val('1');
                }
            }, 300 );

            // Live value
            $( 'form.checkout' ).on( 'change', '#shipping_country', function(){
                var location = $('#shipping_country option:selected').val();
                if ( $.inArray( location, countries ) >= 0 && $(phoneCheck).val() == 0 ) {
                    actionRequire( 'yes' ,phoneField );
                    $(phoneCheck).val('1');
                } else if ( $(phoneCheck).val() == 1 ) {
                    actionRequire( 'no' ,phoneField );
                    $(phoneCheck).val('0');
                }
            });
       })(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' );
}

将代码放在您的活动子主题(或活动主题)的function.php文件中。已经测试并适用于WooCommerce 3.4及以上版本。

相关:


现在给出的结果不稳定,不确定WooCommerce是否发生了冲突或更改了什么,但请查看我的答案以获取更新版本。 - Rich

2
感谢@LoicTheAztec提供的最初的回答,但是该解决方案现在会给出不稳定的结果,并且只是交替切换电话字段的必填和可选状态(开/关)。
原始答案也没有考虑只使用账单地址而没有输入单独的交付或送货地址的客户。
请参见下面的2019年更新版本。
// 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' );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接