Show Content based on Public IP Filtering > WordPress > Show Content based on Public IP Filtering

Just imagine this scenario. Someone has activated Google AdSense for his/her website after getting approval for an AdSense account from Google. However, just three days after the ad was launched, his account became “banned” for the rest of his life due to an “Invalid Click”.

He speculates that many clients were given Internet connection by sharing the same IP address by his Internet Provider.

Some of these users have clicked on the Google Ad on the person’s website. As a result, Google has banned the victim’s AdSense account.

As a result, Google will treat other people’s clicks of the same IP address as the person who created the AdSense account – in simple terms, Google will assume that the publisher himself clicked on his ad, even if he did not click his AD.

Well, this can be an example, but there are instances when you don’t want certain content to be shown to users with certain IP addresses. The following code snippet will help you handle the situation:

 * Get Public IP Address
 * Get the Public IP address of the client.
 * @link
 * @return string The IP Address.
function get_public_ip_address(){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;

 * IP Clearance
 * Make a clearance for IP addresses.
 * @return boolean Clearance true, if not within the range.
function clear_from_blocked_ips() {
	$ip_address 	= get_public_ip_address();
	$blocked_ips  = array(

	if( in_array( $ip_address, $blocked_ips ) )
		return false;
		return true;

There are many versions of the IP tracking function with PHP, I found this function effective most of the time (though sometimes failing).

Also read:  Move WordPress Site from Localhost to Live Server: Step-by-step Tutorial with Screenshots

And, we’ve also created another function wherein we specify the IP constraints that we want to block in the form of arrays (one if one, multiple if multiple).

This function will match the visitor’s IP address in one or more of the IP addresses I am trying to block, if matched, return false, and return true if not found.

And the function can be used like this:

<?php if( clear_from_blocked_ips() ) : ?>
		alert('This content is not blocked for your IP address');
<?php endif; ?>

How to use it in WordPress?

For Themes

You can place both functions in the theme’s functions.php and use them throughout the theme.

For Plugins

You can place both functions in any file of the plugin and use the plugin even throughout the theme.

Category WordPress

Leave Your Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.