Published on

How to show Geo Location Specific Content in WordPress


There might be some cases in which you might want to show geo-specific content, for example showing currency based on the country they are from or some discounts, etc.

And there are multiple SaaS apps for deducting Geo location. However, they do charge a high monthly charge and for our use case, it's an overkill if you're just getting started.

So we'll be building our own custom solution for that and using it in our WordPress site.

Dependency - Geo location Dataset

In order to deduct the country we might need to figure out based on the IP address and its related data.

For the Geolocation dataset (deducting country based on IP) we can use Maxmind's GeoLite2

Get the Account/User ID and License key from it.

And also download the GeoLite2 Free Geolocation Data

Geolocation IP Detection WordPress Plugin

We'll be using Geolocation IP Detection plugin for us to easily switch between multiple datasets easily.

Configure it to use Maxmind's GeoLite2 dataset

Now we can get the country code of a Visitor's IP by invoking the following function.

$geoip = geoip_detect2_get_info_from_current_ip();
$country = $geoip->raw['country']['iso_code']; // US

Adding custom WordPress filter: Is US Region?

We need to add a custom helper on our site for us to easily check whether the user is from the US region.

We're using Code Snippets plugin to add our custom snippets to our site which can be used across the entire site.

Here's the snippet.


function is_us_region() {
    // Make sure this plugin is installed and configured
    $geoip = geoip_detect2_get_info_from_current_ip();
    $country = $geoip->raw['country']['iso_code'];
    return $country === "US";

add_filter('is_us_region', 'is_us_region');
// invoking -> apply_filters ('is_us_region',null);

Invoking apply_filters('is_us_region',null) would return true if the visitor is from US.

Happy Geo-specific content!