Last active
February 24, 2025 13:39
-
-
Save gicolek/bf776153935eb03135041ddf16f24103 to your computer and use it in GitHub Desktop.
Gravity Forms Country Geolocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'gform_after_submission', 'gf_set_country_field_value', 10, 2 ); | |
/** | |
* Set the field value of the user country field | |
* | |
* @hook gform_after_submission | |
**/ | |
function gf_set_country_field_value( $entry, $form ) { | |
$ip = rgar( $entry, 'ip' ); | |
$country = ''; | |
if( $ip == filter_var( $ip, FILTER_VALIDATE_IP ) and !empty( $ip ) ) { | |
// note: the provided token is a random code, create an account yourself to obtain a correct token | |
$ipinfo_request = wp_remote_get( 'https://ipinfo.io/' . $ip . '?token=e55345345' ); | |
if ( is_array( $ipinfo_request ) && ! is_wp_error( $ipinfo_request ) ) { | |
$headers = $ipinfo_request['headers']; // array of http header lines | |
$body = $ipinfo_request['body']; // use the content | |
$body_arr = json_decode( $body, true ); | |
$country = $body_arr['country']; | |
} else { | |
GFCommon::log_debug( 'Error requesting ipinfo api, see: https://ipinfo.io/developers' ); | |
$country = 'ERROR: https://ipinfo.io/developers'; | |
} | |
} | |
$current_form_id = rgar( $form, 'id' ); | |
if( $current_form_id == 1 ) { | |
$field_id = 4; | |
} | |
// we'll fire this hook only for the form ID=1 and the field_id=4. We'll ignore all other forms. | |
if( $field_id ) { | |
$updated_entry = GFAPI::get_entry( $entry['id'] ); | |
$updated_entry[$field_id] = $country; | |
$updated = GFAPI::update_entry( $updated_entry ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment