Changing Available States in Dropdown on Checkout Page using Webhooks

Share
Blog Featured Image 1

As a versatile plugin, WooCommerce provides the option to allow businesses to expand into other regions by enabling shipping to multiple states and countries. However, more often than not, many find the need to limit the selction of a country’s states due to logistical restrictions. 

WooCommerce does a good job blocking off states that are selected by the user, but aren’t made available by the administrator by throwing  “Please choose another state as we do not ship here” message. Although it serves the purpose of getting the user to choose another state, it increases the number of clicks it takes for a potential customer to reach the end goal of purchasing a product, hence damaging the overall user experience. One way to resolve this WooCommerce issue is to use States Webhooks to hide unavailable states. 

In the theme functions.php, simply add in the following code:  

function custom_woocommerce_states( $states ) { 
  $states['MY'] = array( 
    'JHR' => __( 'Johor', 'woocommerce' ), 
    'KDH' => __( 'Kedah', 'woocommerce' ), 
    'KTN' => __( 'Kelantan', 'woocommerce' ), 
    'MLK' => __( 'Malacca (Melaka)', 'woocommerce' ), 
    'NSN' => __( 'Negeri Sembilan', 'woocommerce' ), 
    'PHG' => __( 'Pahang', 'woocommerce' ), 
    'PNG' => __( 'Penang (Pulau Pinang)', 'woocommerce' ),  
    'PRK' => __( 'Perak', 'woocommerce' ), 
    'PLS' => __( 'Perlis', 'woocommerce' ), 
    'SBH' => __( 'Sabah', 'woocommerce' ), 
    'SWK' => __( 'Sarawak', 'woocommerce' ), 
    'SGR' => __( 'Selangor', 'woocommerce' ),   
    'TRG' => __( 'Terengganu', 'woocommerce' ), 
   ); 
  return $states; 
} 

add_filter( 'woocommerce_states', 'custom_woocommerce_states' ); 

Function Explanation: 

Step 1 – Create a function called custom_woocommerce_states and allow the input of a variable called states. 

Step 2 – In states, we want to declare the country “Malaysia”, which is indicated by ‘MY’ and we declare that it is an array as all the states are stored in the array.  

Step 3 – In the array, we choose the states that we want to show in the front end and remove any state you wish to hide. 

Tips: For state id, you can log in to your cPanel and navigate to this file directory: wp-plugins/woocommerce/i18n/states/country.php.  

If you require any assistance, feel free to drop an email to kiatkoh@gmail.com or click here to send me a message!