Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.7k views
in Technique[技术] by (71.8m points)

php - Show or hide checkout postcode field based on chosen city in WooCommerce

In Woocommerce, I am trying to hide the checkout postcode field if a specific city field is selected. I found a working code that hides the billing phone if company field is empty:

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

I don't know how to alter this code to make the required postcode field to be hidden when a specific billing city is selected. Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a bit much more complicated and you will need to define the city in the last function.

The following code handles multiple necessary tasks to show / hide the postcode field based on a specific defined selected city:

// Make postcode field optional
add_filter( 'woocommerce_default_address_fields',  'customizing_checkout_fields' );
function customizing_checkout_fields( $fields ) {
    if( is_checkout() ) {
        $fields['postcode']['required'] = false;
    }
    return $fields;
}

// Replace "(optional)" text by required "*"
add_filter( 'woocommerce_form_field' , 'replace_checkout_optional_by_required', 10, 4 );
function replace_checkout_optional_by_required( $field, $key, $args, $value ) {
    // Only on checkout page for postcode field
    if( is_checkout() && ! is_wc_endpoint_url() && in_array($key, ['billing_postcode', 'shipping_postcode']) ) {
        $optional = '<span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
        $required = '<abbr class="required" title="required">*</abbr>';
        $field = str_replace( $optional, $required, $field );
    }
    return $field;
}

// Hidden input fields for Postcode validation when it's visible
add_action( 'woocommerce_after_order_notes', 'checkout_hidden_field_for_validation', 10, 1 );
function checkout_hidden_field_for_validation( $checkout ) {
    // Hidden field for the phone number validation
    echo '<input type="hidden" name="billing_postcode_check" id="billing_postcode_check" value="">
          <input type="hidden" name="shipping_postcode_check" id="shipping_postcode_check" value="">';
}

// Postcode field validation when it's visible
add_action('woocommerce_checkout_process', 'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
    if( isset($_POST['billing_postcode_check']) && $_POST['billing_postcode_check'] === 'yes' 
    && isset($_POST['billing_postcode']) && empty($_POST['billing_postcode']) ) {
        wc_add_notice( __("The billing postcode field is a required field.", "woocommerce"), 'error' );
    }

    if( isset($_POST['shipping_postcode_check']) && $_POST['shipping_postcode_check'] === 'yes' 
    && isset($_POST['shipping_postcode']) && empty($_POST['shipping_postcode']) ) {
        wc_add_notice( __("The shipping postcode is a required field.", "woocommerce"), 'error' );
    }
}

// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
    // Only on checkout page
     if ( is_checkout() && ! is_wc_endpoint_url() ) :

     // HERE define the city that will hide postcode field
     $city = 'Paris';

     $required = '&nbsp;<abbr class="required" title="required">*</abbr>';
    ?>
    <script>
        jQuery(function($){
            var bc   = '#billing_city_field input',
                sc   = '#shipping_city_field input',
                bp   = '#billing_postcode_field',
                sp   = '#shipping_postcode_field',
                bpc  = '#billing_postcode_check',
                spc  = '#shipping_postcode_check',
                city = '<?php echo $city; ?>',
                req  = '<?php echo $required; ?>';

            // On "update" checkout form event, replace "(optional)" by required "*"
            $(document.body).on('update_checkout', function(){
                $('#billing_postcode_field label > .optional').replaceWith(req);
            });

            // Function that shows or hide checkout fields
            function showHide( selector = '', action = 'show' ){
                var check = selector == bp ? $(bpc) : $(spc);
                if( action == 'show' )
                    $(selector).show( 200, function(){
                        $(this).addClass("validate-required");
                        check.val('yes');
                    });
                else
                    $(selector).hide( 200, function(){
                        $(this).removeClass("validate-required");
                        check.val('');
                    });
                $(selector).removeClass("woocommerce-validated");
                $(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
            }

            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );

            // 2. Change live event:  Show/hide based on city change

            $( 'form.checkout' ).on( 'change input', bc, function() { // Billing field
                if( $(bc).val() === city )
                    showHide( bp, 'hide' );
                else
                    showHide( bp );
            });

            $( 'form.checkout' ).on( 'change input', sc, function() { // Shipping field
                if( $(sc).val() === city )
                    showHide( sp, 'hide' );
                else
                    showHide( sp );
            });
        });
    </script>
    <?php
    endif;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Some related answers:


Hidding billing and shipping postcode on load:

Replace:

            // 1. Initialising (on load): Show/hide based on customer city

            // Billing field
            if( $(bc).val() === city || $(bc).val() == '' )
                showHide( bp, 'hide' );
            else
                showHide( bp );

            // Shipping field
            if( $(sc).val() === city || $(sc).val() == '' )
                showHide( sp, 'hide' );
            else
                showHide( sp );

by:

            // 1. Initialising (on load): Hide postcode

            showHide( bp, 'hide' ); // Billing field
            showHide( sp, 'hide' ); // Shipping field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...