Friday 26 February 2016

How to Add Maxmind IP redirecting to your Drupal 7 theme

This is using GeoIP2 Precision - information on this can be found at http://dev.maxmind.com/geoip/geoip2/web-services Just a quick note on what you’ll need. 1. Some Credits in your Maxmind account http://www.maxmind.com/en/geoip2-precision-services 2. Your domain needs to be on the Javascript Domains list. In your Drupal Template either in template.php or in page.preprocess.php

we need to add the maxmind js .

drupal_add_js('http://js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js', 'external');

In my code I’ve wrapper this in a check to see what page we’re on as I only need it on the front page.

In the themes .info file we have added the line to include this script

scripts[] = js/custom/rcni.maxmind.js

Here’s my code for that file. This is just a either UK or Rest of the World split.
If the page is the same that we are on then we’ll go no where.
And I’ve also made it so to activate this check we’ll add the class ‘ipswitch’ to the page we want it on.


(function ($) {
Drupal.behaviors.rcniMaxmind = {
attach: function (context, settings) {

// this code only needs to run once on landing.

if ( $( "body" ).hasClass( "ipswitch" ) ) {
var redirect = (function () {
/* This implements the actual redirection. */
var redirectBrowser = function (site) {
var uri = 'http://' + window.location.host + '/' + site;
window.location = uri;
};

/* These are the country codes for the countries we have sites for.
* We will check to see if a visitor is coming from one of these countries.
* If they are, we redirect them to the country-specific site. If not, we
* redirect them to world.example.com */
var sites = {
"gb": true
};
var defaultSite = "row";
var onSuccess = function (geoipResponse) {

var site;
/* There's no guarantee that a successful response object
* has any particular property, so we need to code defensively. */
if (!geoipResponse.country.iso_code) {
redirectBrowser("gb");
return;
}
/* ISO country codes are in upper case. */
var code = geoipResponse.country.iso_code.toLowerCase();

if (sites[code]) {
if (code == 'gb') {
site = "uk/home"
var currentLoc = window.location.pathname;
var pathCheck = '/' + site;

if ( window.location.pathname === pathCheck) {
console.log('do nothing');
return;
}
else {
redirectBrowser(site);
}

}
}
else {
site = "row/home"
redirectBrowser(site);
}
};

/* We don't really care what the error is, we'll send them
* to the default site. */
var onError = function (error) {
redirectBrowser("uk/home");
};

return function () {
geoip2.country(onSuccess, onError);
};
}());

redirect();
}
}
};
})(jQuery);

No comments: