Geo-targeted blocks based on visitor IP with Drupal 7

June 9, 2012

Ever needed to show one set of ads to visitors in one region and another set to those in another region?

Here’s how, using Drupal 7 and the ip2country module.

  1. Install https://drupal.org/project/ip2country.
  2. Create or edit a block that you wish to restrict.

Here is some sample code that goes in the block’s “Show block on specific pages” area. The country codes are two-letter, all-caps codes. Capitalization IS important.

Middle East / North Africa

<?php
$detectedcountry = module_invoke('ip2country','get_country',$_SERVER['REMOTE_ADDR']);
$mideast = array('AM', 'AZ', 'BH', 'GE', 'IR', 'IQ', 'IL', 'JO', 'KW', 'LB', 'NT', 'OM', 'QA', 'SA', 'SY', 'TR', 'TM', 'AE', 'YE', 'SO', 'DZ', 'MA', 'TN', 'EG', 'LY', 'CY');
if(in_array($detectedcountry,$mideast)){
return true;
}
?>

US/Canada:

<?php
$detectedcountry = module_invoke('ip2country','get_country',$_SERVER['REMOTE_ADDR']);
$uscanada = array(
'US', 'CA', 'GU', 'FM', 'AS', 'VI', 'PR'
);
if(in_array($detectedcountry,$uscanada)){
return true;
}
?>