其实在WordPress中插入谷歌广告应该是最简单的,可以选择插件也可以直接选择插入代码,而关键是你希望以怎样的形式呈现广告。
对于新手来说,如果搞不清楚要将广告放在哪里,甚至可以直接使用谷歌的自动广告方式,它会见缝插针地在页面中穿内容,当然这种形式可能会给浏览者带来不好的体验。
根据自己的需要,首先尝试的是在侧边栏中加入广告,这种方式可能不会被浏览者注意到或者说不会被误点(毕竟广告收入是需要点击的),但减少了对页面的污染,方法也最简单。
下面的方式只针对如何插入广告代码,至于如何申请谷歌广告不做详细展开。
进入WordPress后台,依次点击外观->小工具,然后在特定小工具(比如我使用的主题中Primary代表了文章中的侧边栏小工具)中插入自定义HTML代码:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxx"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-xxxxxxxxxxx"
data-ad-slot="xxxxxx"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
如下图所示:
上述代码来自谷歌广告的单元广告代码,可以根据自己的需要进行调整。
保存后,静待一段时间等谷歌广告生成。最终效果如下:
如果需要自动广告的话,可以在主题的header.php文件代码中插入<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxx" crossorigin="anonymous"></script>即可。
如果要避免在主页中显示广告,并结合广告则可以添加如下代码:
<!-- Google AdSense(首页中显示广告) -->
<?php if(!is_home() && !is_front_page()){ ?>
<script>
function downloadJSAtOnload() {
var element = document.createElement("script");
element.setAttribute("async", "");
element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxx";
element.setAttribute("crossorigin", "anonymous");
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
<?php } ?>
如果要对登录用户不显示也可以将上面的if(!is_home() && !is_front_page())修改成if (!$user_ID)或者是if (!$user_ID && !isset($_COOKIE['comment_author_'.COOKIEHASH])),前者不对登录用户显示,后者不对登录用户及评论者显示。
参考资料:
优化 Google Adsense 广告代码,提升网站加载速度
Wordpress对评论者不显示Google Adsense广告的设置