Search code examples
phpwordpresswoocommercestatecountries

Remove specific states of a country on Woocommerce Checkout


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?


Solution

  • 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: