Gravity Forms countries restricted by WooCommerce countries

When we use Gravity Forms as a profile editor for our WooCommerce customers, it’s always best that both plugins agree on the details. If WooCommerce is restricting which countries it sells to, then Gravity Forms should probably restrict its addresses to match.

WooCommerce also stores country and state/province details in the customer profile as codes; my plugin Gravity Forms Address Enhanced helps to maintain that connection in Gravity Forms. To restrict Gravity Forms countries to only those supported by WooCommerce requires a little more code (link below for free plugin).

A country select list with only Australia, Christmas Island, New Zealand, and Norfolk Island. Australia is selected.
Country dropdown with only the required countries

Gravity Forms has a filter hook we can use to restrict its selection of countries: gform_countries. It accepts an array of country names, indexed by sequential numbers. NB: names, not codes; this can be important if WooCommerce country names differ, either in US English or in the website’s local translation. With GF Address Enhanced installed, it’s easy to manage that difference by matching the WooCommerce country code to the Gravity Forms country name.

/**
 * restrict which countries are available in Address field
 * @param array $countries
 * @return array
 */
add_filter('gform_countries', function($countries) {
    $wc_countries = new WC_Countries();
    $woo_countries = $wc_countries->get_allowed_countries();

    if ($woo_countries) {
        // build a list of Gravity Forms country names (which might differ from WooCommerce names)
        $countries = [];
        foreach (array_keys($woo_countries) as $code) {
            $countries[] = get_country_name($code);
        }
    }

    return $countries;
});

Gravity Forms Address Enhanced will still load the states and provinces data for all supported countries, however; it would be nice to have it only load data for the required countries, so here’s another code snippet for that.

/**
 * restrict which countries have Smart States data loaded for them
 */
add_filter('gf_address_enhanced_smart_states_countries', function(array $countries) : array {
    $wc_countries = new WC_Countries();
    $woo_countries = $wc_countries->get_allowed_countries();

    if ($woo_countries) {
        // map Gravity Forms country name to country code
        $countries = [];
        foreach (array_keys($woo_countries) as $code) {
            $countries[get_country_name($code)] = $code;
        }
    }

    return $countries;
});

I’ve packaged those two filter hooks up in a simple plugin which you can download from Gist. It will ensure that Gravity Forms on our shop will only offer countries that WooCommerce supports.