Close
Article

Geolocation with WP Engine caching

As many of you probably know, WP Engine implements some very aggressive caching which can have some impressive effects on page speed and search ranking.

However, it also causes some side effects like making determining a user’s location programmatically very difficult.

I recently tackled this issue when writing a plugin that makes some use of geo-location to limit content visibility. Because I wanted to code to be versatile and work on or off WP Engine, I had to come up with a method of doing so.

This is what I eventually came up with:

function get_visitor_country() {
    // We need custom code to accommodate for WP Engines aggressive caching, therefore we need to use WP Engine GeoTarget on WP Engine. This provides future proofing if the host is ever changed.

    $wpe_getuser_country = getenv('HTTP_GEOIP_COUNTRY_CODE'); // This is unique to WPE Engine, so if it returns a value we can assume we're on WP Engine and if nothing is returned, then we're not.

    if($wpe_getuser_country != ''){

        $user_country = $wpe_getuser_country;

    } else {

        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipaddress .= $_SERVER['HTTP_CLIENT_IP'] . ' - ';
        }
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipaddress .= $_SERVER['HTTP_X_FORWARDED_FOR']. ' - ';
        }
        if(isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ipaddress .= $_SERVER['HTTP_X_FORWARDED']. ' - ';
        }
        if(isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ipaddress .= $_SERVER['HTTP_FORWARDED_FOR']. ' - ';
        }
        if(isset($_SERVER['HTTP_FORWARDED'])) {
            $ipaddress .= $_SERVER['HTTP_FORWARDED']. ' - ';
        }
        if(isset($_SERVER['REMOTE_ADDR'])) {
            $ipaddress .= $_SERVER['REMOTE_ADDR']. ' - ';
        }
        if($ipaddress == '') {
            $ipaddress = 'UNKNOWN';
        }   

        if($ipaddress == 'UNKNOWN'){
            $user_ip = '';
        } else {
            $user_ip = $ipaddress;
        }
        $countryArray = json_decode(file_get_contents('http://www.geoplugin.net/json.gp?ip='.$user_ip));
        $user_country = $countryArray->geoplugin_countryName.'!';

    }

    return $user_country;

}

$final_user_country = get_visitor_country();

This is environmentally aware, meaning if you utilize it on a website that is hosted with WP-Engine and later move that website to another host, your geo-targeted content will continue to function.

Questions? Comments?

Let me know below in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *