Gravity Forms and WooCommerce country codes

This post is more than 6 years old.

Gravity Forms and its User Registration add-on make it really easy to create custom registration pages. One problem you’ll hit if you combine that with WooCommerce is that WooCommerce uses standard country codes, but Gravity Forms uses country names. But that can be fixed.

Actually, it’s a bit worse than that: Gravity Forms uses the translated country name, so if you mix multiple languages on your website, you could end up with one customer registered with the country name in English, and another with their country name in Spanish! That could be a little tricky to accommodate 🙂

But there’s an easy fix. Gravity Forms User Registration has a filter hook that lets you convert the country name back into its standard country code, so that you can save that in the WordPress users table. Then WooCommerce will be happy!

Update: included in Gravity Forms Address Enhanced!

/**
* set the country field to a country code, not the country name
* @link https://docs.gravityforms.com/gform_user_registration_prepared_value/
* @param string $value
* @param GF_Field $field
* @param string $input_id
* @param array $entry
* @return string
*/
add_filter('gform_user_registration_prepared_value', function($value, $field, $input_id, $entry) {
    if ($field->type === 'address' && $input_id === $field->id . '.6') {
        $value = $field->get_country_code($value);
    }

    return $value;
}, 10, 4);

Job is done in Gravity Forms, and works in WooCommerce. Gravity Forms entries show the nice human-friendly country name, and WooCommerce country drop-downs pick up the correct country. Everyone is happy!