gform_countries

Description

This filter can be used to add or remove countries from the address field Country drop down.

Usage

add_filter( 'gform_countries', 'your_function_name' );

Parameters

  • $countries array

    The array to be filtered. It contains The list of countries in a standard array (see sample below).

array( 'Argentina', 'Brazil', 'Netherlands', 'United States', 'United Kingdom', ... );

Examples

Limit to Specific Countries

This example demonstrates how to limit the country drop down to only a few select countries.

add_filter( 'gform_countries', function( $countries ) {
	return array( 'Brazil', 'United States', 'Netherlands', 'United Kingdom' );
} );

Add New Countries

This example demonstrates how to add new countries to the list.

add_filter( 'gform_countries', function ( $countries ) {
	$countries[] = 'Country 1';
	$countries[] = 'Country 2';

	asort( $countries );

	return $countries;
} );

Use Country Code as Value

These examples show how you can update the countries list to use the country code as the choice value.

The following example requires Gravity Forms 2.4.19.3+.

add_filter( 'gform_countries', function () {
	$countries = GF_Fields::get( 'address' )->get_default_countries();
	asort( $countries );

	return $countries;
} );

The following example works with Gravity Forms 1.9+.

add_filter( 'gform_countries', function ( $countries ) {
	$new_countries = array();

	foreach ( $countries as $country ) {
		$code                   = GF_Fields::get( 'address' )->get_country_code( $country );
		$new_countries[ $code ] = $country;
	}

	return $new_countries;
} );

Improved Sorting of Translated Countries

The standard PHP sorting functions struggle with strings that have accented and special characters. To solve this issue, you can use the PHP Collator class, which provides better support for sorting such strings. If your site doesn’t have access to the PHP Collator class, the following function will return the default countries list.

add_filter( 'gform_countries', function ( $countries ) {
	if ( ! class_exists( 'Collator' ) ) {
		return $countries;
	}

	$collator = new Collator( get_user_locale() );
	$collator->asort( $countries );

	return $countries;
} );

Placement

This code should be placed in the functions.php file of your active theme.

Source Code

This filter is located in GF_Field_Address::get_countries() in includes/fields/class-gf-field-address.php.