Skip to content

Instantly share code, notes, and snippets.

@spivurno
Created February 18, 2013 02:29
Show Gist options
  • Save spivurno/4974784 to your computer and use it in GitHub Desktop.
Save spivurno/4974784 to your computer and use it in GitHub Desktop.
Gravity Wiz: Geo IP
<?php
/**
* Gravity Wiz Geo IP
*
* Allows the use of the {geoip} merge tag in the dynamic population parameter of any single input field.
* Additionally, provides ability to populate specific properties from the geo data as follows:
*
* :city Virginia Beach
* :region_code VA
* :region_name Virginia
* :metrocode 544
* :zipcode 23462
* :longitude -76.1464
* :latitude 36.8372
* :country_code US
* :ip 74.110.104.59
* :country_name United States
*
* Any of the following filters can be used like so:
*
* {geoip:city}
*
*/
class GWGeoIP {
public static $geo_data;
public static function init() {
add_filter('gform_pre_submission', array('GWGeoIP', 'replace_merge_tag'), 9);
}
public static function replace_merge_tag($form) {
foreach($form['fields'] as $field) {
preg_match_all('/{geoip(:(.+))?}/mi', rgar($field, 'inputName'), $matches, PREG_SET_ORDER);
if(!empty($matches)) {
$data = self::get_geo_data();
list($merge_tag,,$property) = array_pad($matches[0], 3, '');
if($property) {
$_POST["input_{$field['id']}"] = $data->$property;
} else {
$_POST["input_{$field['id']}"] = "{$data->city}, {$data->region_name} {$data->zipcode}";
}
}
}
}
public static function get_ip() {
$ip = RGFormsModel::get_ip();
return $ip != '127.0.0.1' ? $ip : '74.110.104.59';
}
public static function get_geo_data() {
if(empty(self::$geo_data)) {
$geo_data = json_decode( wp_remote_retrieve_body( wp_remote_get( 'http://freegeoip.net/json/' . self::get_ip() ) ) );
} else {
$geo_data = self::$geo_data;
}
return $geo_data;
}
}
GWGeoIP::init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment