GeoIP targeting and wordpress problem

by 2 replies
3
Hey. I want to do something for one of my sites: not display AdSense results for users came from a certain country.

To do that, I got 2 files from maxmind: GeoIP.dat and geoip.inc, which can be used to return the visitor's location based on ip. A friend gave me this code, which I doesn't work properly:

In header.php:
<?php
include("geoip.inc");
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$ip=$_SERVER['REMOTE_ADDR'];
$cc=geoip_country_code_by_addr($gi, $ip);
geoip_close($gi);
?>

Wherever I want adsense (index.php):

<?php if ($cc<>"US"): ?>
The adsense code HERE
<?php endif; ?>

The problem is that if I place the code echo $cc in the header it will show my country, but it won't work in index.php

Anyone knows why ?
#programming #geoip #problem #targeting #wordpress
  • It's because the $cc variable isn't global in scope. In other words, its value doesn't travel beyond the actual file that its value is declared in.

    Probably the easiest way to accomplish what you want is to turn your code into a function that tests the IP address and returns true or false, put it in your theme's functions.php file, then test against it in your theme code.
  • I've placed this: global $cc; before my code and it seems to work for now. Will do some more testing later.

    Thanks, I really appreciate your help.

Next Topics on Trending Feed

  • 3

    Hey. I want to do something for one of my sites: not display AdSense results for users came from a certain country. To do that, I got 2 files from maxmind: GeoIP.dat and geoip.inc, which can be used to return the visitor's location based on ip. A friend gave me this code, which I doesn't work properly: