Hướng dẫn Modify the Shipping States for a selected country in WooCommerce

Written by admin
Posted on Tue, 08/03/2021 - 03:06
30 views

Share Everywhere

Table of contents

You can modify the shipping states for a selected country in WooCommerce. To achieve this, simply insert the below-given code snippet to the functions.php of your active child theme file.

add_action( 'wp_footer', 'webtoffee_checkout_shipping_filter_it_states' );
   
function webtoffee_checkout_shipping_filter_it_states() {
   if ( ! is_checkout() ) {
      return;
   }
   ?>
      
   <script>
   jQuery(document).ready(function($) {
 
      $(document.body).on('country_to_state_changed', function() {
 
         var $shipping_country = $('#shipping_country');
 
         var new_shipping_state = '';
 
         switch($shipping_country.val()) {
            case 'IT':
               new_shipping_state =  {'TV': "Treviso", "CA": "Carità", "Cs": "Castrette"};
               break;
         }
 
             if( ! $.isEmptyObject(new_shipping_state)) {
                
                var optionsAsString = "";
                for (var key in new_shipping_state) {
                    optionsAsString += "<option value='" + key + "'>" + new_shipping_state[key] + "</option>";
                }
                $( 'select[name="shipping_state"]' ).html( optionsAsString );
                
             } 
 
      });
 
   });  
   </script>
       
   <?php
}

To modify both shipping and billing states for a selected country, you can use the below-given code snippet:

/**
 * Add or modify WooCommerce States
 */
 
add_filter( 'woocommerce_states', 'webtoffee_woocommerce_states' );

function webtoffee_woocommerce_states( $states ) {

  $states['XX'] = array(
    'XX1' => 'State 1', 
    'XX2' => 'State 2',
    'XX3' => 'State 3'
  );

  return $states;
}

You can try to use the following:

add_action('wp_footer', 'cart_country_update_shipping_methods', 50);
function cart_country_update_shipping_methods() {
    if ( ! is_cart() ) return; // On cart
    ?>
    <script type='text/javascript'>
        jQuery(function($){
            $(document.body).on('change', 'select[name="calc_shipping_country"]', function(){
                $(this).submit();
            });
        });
    </script>
    <?php
}

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
11 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”