GeoIP targeting and wordpress problem

2 replies
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 ?
#geoip #problem #targeting #wordpress
  • Profile picture of the author SteveJohnson
    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.
    Signature

    The 2nd Amendment, 1789 - The Original Homeland Security.

    Gun control means never having to say, "I missed you."

    {{ DiscussionBoard.errors[3516785].message }}
  • Profile picture of the author Mo Annuar
    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.
    {{ DiscussionBoard.errors[3516879].message }}

Trending Topics