nooo
nooo

Reputation: 81

How to add new state(s) for a country to WooCommerce?

I want to add new state in WooCommerce. I used woo-state and snippet plugin and added this code:

function woo_add_my_country( $country ) {
   $country["AE-DU"] = 'Dubai';
   return $country;
}
add_filter( 'woocommerce_countries', 'woo_add_my_country', 10, 1 ); 

But still I cannot see it.

How to add new state for a country to WooCommerce?

Upvotes: 3

Views: 1711

Answers (2)

moneeb
moneeb

Reputation: 152

This is how you can add more states to existing list of states for any country.

add_filter( 'woocommerce_states', 'adding_custom_country_states' );
function adding_custom_country_states( $states ) {

     // Define the related country code
     $country_code = 'DE'; 

     // Define for each state a different state code
     $new_states = array(
         'DE-NDS' => __('Lower Saxony', 'woocommerce'),
     );

     // Merge existing states with the new states
     $states[$country_code] += $new_states;

     return $states;
 }

Upvotes: 0

LoicTheAztec
LoicTheAztec

Reputation: 253773

You are not using the right hook and way to do it. Use the following instead:

add_filter('woocommerce_states', 'add_country_states');
function add_country_states( $states ) {
    // If states already exist for "AE" country (add it to existing ones)
    if( isset($states['AE'] ) ) {
        $states['AE']['DU'] = __('Dubai', 'woocommerce');
    }
    // IF states  doesn't exist for "AE" country add the new states
    else {
        // One state by line in the array with its code as key
        $states['AE'] = array(
            'DU' => __('Dubai', 'woocommerce'),
        );
    }
    return $states;
}

And you can add a placeholder to the select field for 'AE' country code like (optional):

add_filter('woocommerce_get_country_locale', 'filter_get_country_locale');
function filter_get_country_locale( $country_locale ) {
    $country_locale['AE']['state']['placeholder'] = __('Select a state', 'woocommerce');

    return $country_locale;
}

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

All Related questions and answers using woocommerce_states hook.

Upvotes: 2

Related Questions