Skip to main content

How To Block Ads Being Shown In Certain Countries

How To Block Ads Being Shown In Certain Countries  阅读原文»

When you run ads on your WordPress site, sometimes you need to block ads being shown in certain countries. That’s what I’m doing to block visitors from some countries viewing ads to protect my Adsense account.

Google Adsense logo Image source: Google Adsense Blog

Traffic source from some certain countries may harm your Google Adsense account.

In this tutorial, I’ll show you how to write your own WordPress plugin to do it. I won’t try to build a complex plugin, but keep it simple; and sure, you can develop it to meet your needs. Let’s begin.

First of all, you need list of IP Ranges of the countries you need to block. For example, this is the US’ IP ranges. You can search these kinds of ranges easily on the Internet.

  3.0.0.0 - 4.17.135.31  4.17.135.64 - 4.17.142.255  4.17.143.16 - 4.18.32.71  4.18.32.80 - 4.18.40.135   ...

How it works? I’ll use WordPress Shortcode to display ads, once there are requests from these IPs, the plugin won’t show ads.

You can leave the IPs in the plugin file, but I prefer push them into database, working on database will make the plugin loads much faster.

We use ip2long() to convert the IPs to numbers and insert them to a table in the database:

$range = "3.0.0.0 - 4.17.135.31  4.17.135.64 - 4.17.142.255  4.17.143.16 - 4.18.32.71  4.18.32.80 - 4.18.40.135  ... "; // // Paste all the IP ranges. These are just sample ranges
                 $range=str_replace(" ","",$range);   $range = str_replace ("-",",",$range);   $range = str_replace ("\n",",",$range);   $range = explode(",",$range);
  for ($i=0;$i<=count($range);$i++) { $ipaton[$i] = sprintf("%u", ip2long($range[$i])); $ipaton[$i] = (substr($range[$i],0,3)>127) ? ((ip2long($range[$i])                & 0x7FFFFFFF) + 0x80000000) : ip2long($range[$i]); //The above two lines were broken to fit the theme's width! //It's just one line  }
  $i=0;   while ($i<count($range)) {   $s = $i+1;   $firstip[] = $ipaton[$i];   $lastip[] = $ipaton[$s];   $i=$i+1;   $i++;   }

The $firstip[] and $lastip[] of the ranges above is now something like this:

$firstip[$i] $lastip[$i]  0185088  20447231  234885120  234889215  245366784  247463935  249561088  251658239  452987904  452988927  ...

When there is a IP requests your page, the plugin will convert that IP to number using ip2long() then a function will check if the IP is between the $firstip[] and $lastip[]. Here is that function:

function blockip_check() {  global $wpdb;   $ip = $_SERVER['REMOTE_ADDR'];   $ip_aton = sprintf("%u", ip2long($ip));   $ip_aton = (substr($ip,0,3)>127) ?                   ((ip2long($ip) & 0x7FFFFFFF) + 0x80000000)                    : ip2long($ip);        //The above 3 lines were broken to fit the theme's width!        //It's just one line  $sql = "SELECT * FROM wp_blockip   WHERE $ip_aton >= startip   AND $ip_aton <= endip   ORDER BY startip DESC   LIMIT 1";   $row = $wpdb->get_row("$sql");  return $row;  }

The function return $row, if $row is empty, that means the visitor's IP is not in the table, the plugin then display ads.

$check = blockip_check();  if (empty($check)){   function ads1() {   return ''; //Display ads with no content!   }  add_shortcode( 'ads1', 'ads1' );   //If you have more ads spot, make a copy of ads1() here!
} else {
function ads1() {   return 'Ads Content 1';                  //Replace Adsense code or any ads code here!  }  add_shortcode( 'ads1', 'ads1' ); // Now you can put [ads1] to your theme or widget to display ads1 // If you have more ads spot, make a copy of ads1() here!  }

Once the plugin is activated, you can use put [ads1], [ads2]… anywhere in your theme or widget to display ads.

It’s just that simple! Let's put all together and make a complete plugin.

  1. Create a .php file and put it under the plugins folder. For example: /plugins/blockip/blockip.php
  2. Edit the source code below to meet your needs. (Change ads code, IP ranges… )
  3. Activate the plugin through the admin board.
  4. Use WordPress Shortcode to display ads, by place [yourads] in your themes or widgets.
<?php /* Plugin Name: Block IP Plugin URI: http://wordpress.com/ Description: Block ads being shown in certain countries. Version: 1.0.0 Author: nn_bien@yahoo.com Author URI: http://wordpress.com/ */  add_filter('widget_text', 'do_shortcode');  function blockip_install() { global $wpdb;  $table_name = $wpdb->prefix . "blockip"; //Your table name   $range = "3.0.0.0 - 4.17.135.31 4.17.135.64 - 4.17.142.255 4.17.143.16 - 4.18.32.71 4.18.32.80 - 4.18.40.135"; // These are sample ranges   $range=str_replace(" ","",$range);  $range = str_replace ("-",",",$range);  $range = str_replace ("\n",",",$range);  $range = explode(",",$range);   for ($i=0;$i<=count($range);$i++) {  $ipaton[$i] = sprintf("%u", ip2long($range[$i]));  $ipaton[$i] = (substr($range[$i],0,3)>127) ?                  ((ip2long($range[$i]) & 0x7FFFFFFF) + 0x80000000)                  : ip2long($range[$i]); //The above 3 lines were broken to fit the theme's width! //It's just one line  }  $i=0;  while ($i<count($range)) {   $s = $i+1;   $firstip[] = $ipaton[$i];   $lastip[] = $ipaton[$s];   $i=$i+1;   $i++;  }  if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name){  $sql = "CREATE TABLE " . $table_name . " (   startip int(11) unsigned NOT NULL default '0',   endip int(11) unsigned NOT NULL default '0',   KEY startip (startip)   );";  require_once(ABSPATH . 'wp-admin/includes/upgrade.php');  dbDelta($sql);   $i=0; while ($i<count($range)/2){     $rows_affected = $wpdb->insert($table_name,                             array('startip' => $firstip[$i],                                   'endip' => $lastip[$i]));      //The above 3 lines were broken to fit the theme's width!      //It's just one line  $i++;   }  } }   register_activation_hook(__FILE__,'blockip_install');  function blockip_check() { global $wpdb;  $ip = $_SERVER['REMOTE_ADDR'];  $ip_aton = sprintf("%u", ip2long($ip));  $ip_aton = (substr($ip,0,3)>127) ? ((ip2long($ip) & 0x7FFFFFFF)                + 0x80000000) : ip2long($ip);     //The above two lines were broken to fit the theme's width!     //It's just one line  $sql = "SELECT * FROM wp_blockip    WHERE $ip_aton >= startip    AND $ip_aton <= endip    ORDER BY startip DESC    LIMIT 1";  $row = $wpdb->get_row("$sql"); return $row; }   $check = blockip_check();   if (!empty($check)){     function ads1() {      return '';                     //Display ads with no content!     }    add_shortcode( 'ads1', 'ads1' );     function ads2() {      return '';                     //Display ads with no content!     }    add_shortcode( 'ads2', 'ads2' ); //If you have more ads spot, make a copy of ads2() here!    } else {     function ads1() {      return 'Your Ads Code';             //Replace Adsense code or any ad code here!     }    add_shortcode( 'ads1', 'ads1' ); //Now you can put [ads1] to your theme or widget to display ads1     function ads1() {      return 'Your Ads Code'; //Replace Adsense code or any ad code here!     }    add_shortcode( 'ads2', 'ads2' ); //Now you can put [ads2] to your themes or widgets to display ads2 //If you have more ads spot, make a copy of ads2() here!        }  ?>

If you have any question, please leave comment. I will answer within my knowledge!

阅读更多内容

该邮件由 QQ邮件列表 推送。
如果您不想继续收到该邮件,可点此 退订

Comments

Popular posts from this blog

How to find ideas to post new article in your blog

How to find ideas to post new article in your blog    阅读原文»   It is true that sometimes being a blogger may face situations where I would personally like to call it your brain juices got dried up as you have pretty much ran out of topic to blog and you are in crisis as your readers are anxiously waiting for your new posts but you are unable to give in. That’s when you will probably come with excuses like I just posted last week although that post was more directly towards the newbies who stop themselves from making money but it’s still pretty much the same even though you consider yourself not a newbie. The fact is that ideas are everywhere and I mean everywhere if you know where to find it and know how to leverage it. You may be surprised that sometimes these ideas are just right in front of you but you are not observant enough to convert these ideas and turn it into your blog post. Today I will share some tips on where to get these ideas and most of it is part of your dai

Over A Year After Android Launch, ShopSavvy Finally Comes To The iPhone

ShopSavvy was one of the best early Android applications. It launched in October of last year after winning one of the initial Android Developer Challenge top prizes (when it was still known as GoCart). But despite the success it has seen on Android, one question remained: When would it be available for the iPhone. Today, it finally is. Developed by the guys at Big In Japan , ShopSavvy is an app that allows you to use your device as a portable barcode scanner. You point your phone's camera at any barcode and it will read it, do a product look up, and give you information about the product, as well as where you can find it online or at nearby stores and for how much. Obviously, something like this is a window shopper's dream. ShopSavvy was one of the best early Android applications. It launched in October of last year after winning one of the initial Android Developer Challenge top prizes (when it was still known as GoCart). But despite the success it has seen on Android, o

部门心脏?

i.am.weihua.1234您好!!              生产计划与物料控制PMC高级研修班 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 课程背景: 生产计划和物料控制(PMC)部门是一个企业"心脏", 掌握着企业生产及物料运作的总调度 和命脉,统筹营运资金、物流、信息等动脉,直接涉及影响生产部、生产工程部、采购、货仓、品 控部、开发与设计部、设备工程、人力资源及财务成本预算控制等,其制度和流程决定公司盈利成 败.因此PMC部门和相关管理层必须充分了解:物料计划、请购、物料调度、物料控制(收、发、退、 借、备料等)、生产计划与生产进度控制,并谙熟运用这门管理技术来解决问题,学习拉动计划价 值流(VSM)图,从拉动计划价值流切入剖析工厂制造成本和缩短制造周期 ,提高物流过程循环效 率(库存、资金的周转率)及客户满意率;为降低或消除物流过程中的非增值活动. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 课程目标: 1、建立制定完善的生产与物控运作体系?提升准时交货和降低库存成本 2、预测及制定合理的短、中、长期销售计划?达成公司策略管理目标 3、对自身的生产能力负荷预先进行详细分析并建立完善产品数据机制协助公司建立产品工程数据 4、生产前期做好完整的生产排程和周生产计划?提高备料准确率,保持生产顺畅 5、配合生产计划做到良好物料损耗控制和备料?完善降低物料损耗机制和停工待料工时 6、对生产进度及物料进度及时跟进和沟通协调?缩短生产周期,提高企业竞争力 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 报名详情: 培训时间:2012年11月 3- 4深圳 11月15-16上海 11月22-23北京 12月 1- 2广州 承办单位:新 活 力 顾 问 培训对象:生产计划部门、物料计划部门、采购部门、 生产部门、销售部门、物流、研发部门、 PIE、IT 培训费用:3200元/人(包括资料费、午餐及上下午茶点等) 报名热线:400-623-8399 (免长途话费) 电邮: maomao@xhlpx.com QQ:120915