2

I am trying to find a way to remove a few US states from the "State" dropdown in WooCommerce checkout page.

List of states:

  1. Hawaii
  2. Alaska
  3. Armed Forces (AA)
  4. Armed Forces (AE)
  5. Armed Forces (AP)

What I have been doing so far:
I have been manually removing them as mentioned in this link. But this is not a good way, as the changes get overwritten every time WooCommerce is updated.

Alternative I found: On this link WooCommerce restrict shipping to states based on category, there's a way to set shipping states if specific condition is met. I am wondering if I can unset five states. This sounds more logical to me than setting 50 states. But unfortunately, I am not able to find anything useful.

Any ideas what could be a possible solution?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Danish Muneer
  • 568
  • 1
  • 9
  • 22

2 Answers2

12

The simplest way is to remove them them using the dedicated filter hook woocommerce_states this way:

add_filter( 'woocommerce_states', 'custom_us_states', 10, 1 );
function custom_us_states( $states ) {
    $non_allowed_us_states = array( 'AK', 'HI', 'AA', 'AE', 'AP'); 

    // Loop through your non allowed us states and remove them
    foreach( $non_allowed_us_states as $state_code ) {
        if( isset($states['US'][$state_code]) )
            unset( $states['US'][$state_code] );
    }
    return $states;
}

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

Then you can add some condition or make a custom settings page like in the threads below:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
2

Best way of doing this would be using a filter, add this snippet in your themes functions.php

/**
 * Modify Woocommerce states array
 *
 * @param array $states, collection of all $states
 * @return array $states, modified array.
*/
add_filter( 'woocommerce_states', function( $states ){
    // Unset Hawaii
    unset( $states['US']['HI'] );

    return $states;
}, 999);

You can unset any states like this.

Lennart
  • 639
  • 4
  • 14
  • Some additional info, the prio 999 might not be needed but this ensures that you can also filter any data added by plugins. If you're unsure what key values to use to unset the other states look them up in the sourcefile: https://github.com/woocommerce/woocommerce/blob/master/i18n/states/US.php – Lennart Dec 08 '18 at 00:34
  • Thank you, this works too. The only reason I accepted the other post as the answer is because it's complete with all state codes. – Danish Muneer Dec 10 '18 at 14:40