JavaScript is one of the most important scripting languages used in WordPress, and Geo Controller offers several JavaScript objects that provide instant access to geolocation data.
From version 6.x.x and above, geolocation information is embedded directly in the HTML and made accessible through the following global objects:
window.wp.geo
– Standard WordPresswp
objectwindow.cfgeo
– Direct access via the globalwindow
objectcf.geoplugin
– Legacy object from older versions of Geo Controller (conflict-free from version 6.x.x)
All of these objects return the same geo information, structured like this:
{ url: "https://yourdomain.com/", host: "wpgeocontroller.com", protocol: "https", ip: "217.138.192.36", ip_version: "4", ip_dns: "", ip_dns_host: "", ip_dns_provider: "", ip_number: "3649749028", country_code: "GB", country: "Great Britain", region: "England", region_code: "", city: "United Kingdom", continent: "Europe", continent_code: "EU", address: "United Kingdom, England, Great Britain", area_code: "", dma_code: "", latitude: "51.508529663086", longitude: "-0.12574000656605", timezone: "Europe/Zurich", locale: "en_GB,ga_GB,cy_GB,gd_GB,kw_GB", currency: "GBP", currency_symbol: "£", base_currency: "USD", base_currency_symbol: "$", currency_converter: "0.7684", ip_host: "176.9.103.101", timestamp: "1580845604", timestamp_readable: "Tue, 04 Feb 2020 19:46:52 +0000", current_time: "20:10:57", current_date: "February 4, 2020", version: "7.8.8", is_vat: "1", in_eu: "1", gps: "0", accuracy_radius: "200km", lookup: "unlimited", credit: "These geographic information provides <a href="http://wpgeocontroller.com/" target="_blank">Geo Controller</a>", flag: "https://yourdomain.com/wp-content/plugins/cf-geoplugin/assets/flags/4x3/gb.svg", }
Basic Usage
Here’s a simple usage example that prints the country name to the browser console:
(function(geo){ var city = geo.city, region = geo.region, country = geo.country, ip = geo.ip; console.log(geo.country); }(window.wp.geo || window.cfgeo || cf.geoplugin));
With jQuery or Zepto.js you can directly use the data like this:
(function($){ $('input#address').val(window.cfgeo.address); }(jQuery || window.jQuery || Zepto || window.Zepto));
AJAX & Cache Bypass
In case you are using aggressive page caching or need real-time data, Geo Controller provides a custom AJAX action to fetch geolocation data directly from the plugin.
(function($){ var nonce = 'YOU MUST PROVIDE IT VIA PHP (READ BELOW)'; $.ajax({ method: 'POST', url: ajaxurl + '?action=cfgeo_cache', data: { 'cfgeo_nonce': nonce }, cache: false, async: false }).done(function(data){ console.log(data); }); }(jQuery || window.jQuery || Zepto || window.Zepto));
Nonce Generation
You must generate a valid nonce in PHP and pass it to your JavaScript using wp_localize_script() or via inline HTML.
wp_create_nonce('cfgeo-process-cache-ajax');
If the nonce is missing, the request will fail and geolocation data won’t be returned.