用Custom Field控制Google广告
关键字:Google Ads, Custom Field, Wordpress, get_post_meta()函数
Wordpress是目前最强大的免费动态blog平台,它模块化的结构也方便高级用户进行必要的定制。
今天,我就利用它的Custom Field做了一个对单独Entry的Google广告控制模块。
过程很简体,会的5分钟内就能搞定。
1.首先,要发布Google广告,必须要去Google Adsense申请一个帐号;另外,本方法针对单独entry操作,因此需要模板文件中有针对单一entry的模板(如single.php)。
2.根据Google自己的统计,和文章内容镶嵌在一起的广告会得到较高的点击率,所以我建议在豆腐块文章中,各位站长应该使用125×125或者是120X240的小广告,以便能和文章镶嵌;至于镶嵌的代码,我采用表格嵌套的方式(如下图所示)。

3.利用Wordpress的Custom Field新建一个key,取名为no_ads。当不需要显示Google广告时候,可设置为1,其他情况则无需填写该项值(关于更多custom field的知识请点击本条目前面的链接)。
4.具体代码替换见下:
1)打开single.php,找到显示entry内容的语句
<?php the_content(); ?>
2)将该语句替换为如下语句
<table width="655"> <?php //the big table for content, please change the width by yourself ?>
<tr><td valign="top">
<?php if (get_post_meta($post->ID, no_ads, true)==false) //利用custom field中的no_ads项来判断是否需要显示Google广告
{
?>
<table width="130" align="right">
<tr valign="top" align="right"><td>
<script type="text/javascript"><!--
google_ad_client = "pub-XXXXXXXX"; //你能从Google adsense得到自己的client代号,下面广告的颜色参数请自行更改
google_ad_width = 125;
google_ad_height = 125;
google_ad_format = "125×125_as";
google_ad_type = "text_image";
google_ad_channel ="";
google_color_border = "888888";
google_color_bg = "555555";
google_color_link = "FFCCFF";
google_color_text = "FFFFFF";
google_color_url = "FFFF99";
//--></script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</td></tr>
</table>
<?php
}
?>
<?php the_content(); ?>
</td></tr>
</table>
实际的结果,在我blog上就能看到。本entry单独打开时能看到右侧的Google广告,而另一个entry中,no_ads的值设为1,点击后可以看到google 广告没有被显示。