如何在WordPress所有文章底部批量添加Google AdSense广告代码
想在WordPress网站所有文章底部添加Google AdSense广告代码? Google官方并未提供明确的方法。本文将分享纯代码批量添加的解决方案。
1. 获取Google AdSense广告代码
1.1 选择广告类型
主要有4种广告单元可选:
- 展示广告
- 信息流广告
- 文章内嵌广告
- 多重广告
本文以多重广告单元为例。
1.2 获取广告代码
登录Google AdSense后台,创建广告单元并获取代码。
2. 在WordPress网站添加代码
2.1 添加核心代码
在functions.php文件中添加以下代码:
//在所有文章底部添加谷歌广告 function add_after_post_content($content) { if(!is_feed() && !is_home() && is_singular() && is_main_query()) { $content .= '替换成你的广告代码'; } return $content; } add_filter('the_content', 'add_after_post_content'); 2.2 推荐添加方式一:子主题
后台 > 外观 > 主题文件编辑器 > 子主题 > functions.php > 粘贴代码 > 更新文件
2.3 推荐添加方式二:使用插件
安装Code Snippets插件,后台 > Snippets > Add New > 粘贴代码 > 保存
3. 查看广告效果
添加后等待几分钟,所有文章底部都会显示广告。由于缓存等原因,可能需要稍长时间才能生效。
方法优势:
- 批量处理所有现有文章
- 无需手动逐篇添加
- 高效快捷
扩展应用:
只需修改content内容,即可添加其他元素:
- 版权声明
- 图片广告
- 点赞/打赏功能等
英文版:
To add Google AdSense ads at the bottom of all WordPress posts, follow these steps:
1. Get AdSense Code
Choose ad type (Display, In-feed, In-article, Multiplex) and get the code from AdSense dashboard.
2. Implement in WordPress
Add the provided PHP code to your functions.php file either through:
- Child theme editor
- Code Snippets plugin
3. Verify Implementation
Ads will appear after cache refreshes. This method works for all existing and future posts automatically.
Pro Tip: The same method can be adapted to add other post-footer elements by modifying the content variable.