Reputation: 183
I need to do some very basic geo-targeting for a WordPress site.
Something like:
<?php if ( visitor is from usa ): ?>
<?php get_footer('us'); ?>
<?php else: ?>
<?php get_footer('other-countries'); ?>
<?php endif; ?>
Till now I used the GEO service provided by ip-api.com. My code looks like this:
<?php $ip = $_SERVER['REMOTE_ADDR'];
$query = @unserialize(file_get_contents('http://ip-api.com/php/' . $ip));
$geo = $query['countryCode'];
if( $query['countryCode'] == 'US') : ?>
DO THIS
<?php else: ?>
DO THAT
<?php endif ?>
The problem is that the php unserialize is now deprecated and extremely slow. Ip-api suggest to use JSON instead. But I am a total newbie and I don't know how to achieve the same results with JSON. Can someone please help me?
I know there are various plug-ins out there, but I think they are overkill for the very simple geo targeting I need.
PS: I just learn that I should use the code
$.getJSON( '//ip-api.com/json?callback=?', function( data ) {
console.log( JSON.stringify( data, null, 2 ) );
});
But still I need help to put together the final complete code.
Upvotes: 0
Views: 496
Reputation: 15620
Try this:
<?php
$ip = ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) ?
$_SERVER['REMOTE_ADDR'] : '';
$country_code = '';
if ( $ip ) {
// 'fields' are comma-separated list of fields to include in the response.
// No spaces between the fields. See http://ip-api.com/docs/api:returned_values#field_generator
$url = 'http://ip-api.com/json/' . $ip . '?fields=countryCode,status,message';
$res_body = wp_remote_retrieve_body( wp_safe_remote_get( $url ) );
$geo = json_decode( $res_body );
$country_code = isset( $geo->countryCode ) ? $geo->countryCode : '';
}
if ( 'US' === $country_code ) : ?>
DO THE THIS
<?php else : ?>
DO THE THAT
<?php endif; ?>
PS: I just learn that I should use the code
Yes, that's an example of doing it with jQuery.
Upvotes: 1