Lê Nghĩa
Lê Nghĩa

Reputation: 255

For specific country replace city with the chosen state value in Woocommerce checkout

In Woocommerce, I wrote the code for billing_state to use the shipping charge. Now I want to write the value from billing_state to billing_city, when changing billing_state, billing_city also changes

This are my custom states code:

add_filter( 'woocommerce_states', 'vietnam_cities_woocommerce' );
function vietnam_cities_woocommerce( $states ) {
  $states['VN'] = array(
    'HCM' => __('Hồ Chí Minh', 'woocommerce') ,
    'HANOI' => __('Hà Nội', 'woocommerce') ,
    'HAIPHONG' => __('Hải Phòng', 'woocommerce') ,

  );

  return $states;
}

Any help is appreciated.

Upvotes: 4

Views: 1590

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253773

The following code will fill up the city from the state value when the country is Vietnam (VN) in the checkout page:

// Add checkout custom select fields
add_action( 'wp_footer', 'custom_checkout_city_field', 20, 1 );
function custom_checkout_city_field() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    $country = 'VN'; //  <=== <=== The country code
    // $states   = WC()->countries->get_shipping_country_states()[$country];


    ?>
    <script type="text/javascript">
    jQuery(function($){
        var c = '<?php echo $country; ?>',  f = 'form.checkout';

        // On billing state change
        $(f).on('change', '#billing_state', function(){
            if($('#billing_country').val() == c ){
                $('#billing_city').val($(this).val());
            }
        });

        // On shipping state change
        $(f).on('change', '#shipping_state', function(){
            if($('#shipping_country').val() == c ){
                $('#shipping_city').val($(this).val());
            }
        });
    });
    </script>
    <?php
    endif;
}

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

Upvotes: 3

Related Questions