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
An array of countries using the ISO 3166-1 alpha-2 code as the key to the country name (see sample below).
array(
'AR' => 'Argentina',
'BR' => 'Brazil',
'NL' => 'Netherlands',
'US' => 'United States',
'GB' => '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(
'BR' => 'Brazil',
'US' => 'United States',
'NL' => 'Netherlands',
'GB' => 'United Kingdom',
);
} );
Add New Countries
This example demonstrates how to add new countries to the list.
add_filter( 'gform_countries', function ( $countries ) {
$countries['C1'] = 'Country 1';
$countries['C2'] = 'Country 2';
asort( $countries );
return $countries;
} );
Use Country Code as Value
Gravity Forms 3.0 and newer already use the country codes as the values. So these examples are no longer required.
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;
} );
Move some countries to the top of the list
This example shows how the United Kingdom and United States choices can be moved to the top of the list of countries.
add_filter( 'gform_countries', function ( $countries ) {
unset( $countries['GB'], $countries['US'] );
return array_merge( array(
'GB' => 'United Kingdom',
'US' => 'United States',
), $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.