Remove countries in WooCommerce from an array of defined country codes

I found How to remove specific country in WooCommerce answer code that works for unsetting one country. How can I use it to unset more countries 3-4?

This code works to hide US from my geolocation list. I need it to hide a few more countries based on countrycodes “US”, “UK”, “RU” etc. I know that for checkout it can be done from settings but I need it to remove a few countries for a geolocation plugin that by default shows a list of all countries to choose from.

Answer

The following will remove countries in WooCommerce from an array of defined country codes:

add_filter( 'woocommerce_countries', 'woo_remove_countries' );
function woo_remove_countries( $countries ) {
    // Here set in the array the country codes you from countries you want to remove
    $countries_to_remove = array('US', 'GB', 'RU');

    foreach ( $countries_to_remove as $country_code ) {
        unset($countries[$country_code]);
    }
    return $countries; 
}

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

Leave a Reply

Your email address will not be published. Required fields are marked *