Home > Net >  How to get a list of country codes in WooCommerce
How to get a list of country codes in WooCommerce

Time:05-10

I wonder how to get list of country code [not country names] in WooCommerce?

I've gone through the WooCommerce docs but can't find the code. I know how to get the list of country names from WooCommerce but can't figure out how to get the codes

I am putting a country select box on a custom registration template. Where the select option value should be country code.

Example

$all_countries = $countries_obj->countries; //Country Name array
$all_countries_code = ?????

foreach($all_countries as $ac){
    echo '<option selected value="[country_code]">'.$ac.'</option>';
}

Any help would be appreciated to get the country code array.

CodePudding user response:

You can use WC()->countries->get_countries() and then use the array key

So you get:

// Get all countries key/names in an array:
$countries = WC()->countries->get_countries();

echo '<select name="countries">';

foreach ( $countries as $code => $country ) {
    echo '<option value="' . $code . '">' . $code . '</option>';
}

echo '</select>';

  • $countries = countries keys/names in an array
  • $code = country code (key)
  • $country = country name
  • Related