建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

纯代码批量给WordPress网站所有文章底部添加谷歌Adsense广告(wordpress调用特定文章列表的技巧分享)

GG网络技术分享 2025-03-18 16:14 2


纯代码批量给WordPress网站所有文章底部添加谷歌Adsense广告

如果想在WordPress网站所有文章底部添加谷歌adsense广告代码,如何操作?谷歌adsense官方没有给出明确的方法。本文就来分享下方法,纯代码批量给所有文章添加谷歌adsense广告。

1.获取谷歌adsense广告代码

1.1首先你需要想清楚在文章底部添加什么类型的谷歌广告单元,主要有4种:

  • 展示广告
  • 信息流广告
  • 文章内嵌广告
  • 多重广告

哪种广告效果好,真的没有完全确定的答案。本文以添加多重广告单元为例。

1.2进入谷歌adsense后台,创建想要的谷歌adsense广告单元,并获取广告单元代码。

2.WordPress网站添加代码

2.1登录我们在WordPress网站后台,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文件中添加代码

后台》外观》主题文件编辑器》子主题》functions.php》粘贴代码》更新文件

2.3添加位置建议二:code snippets插件中添加代码

后台》snippets》add new》编写标题》粘贴代码》save changes,点击生效

3.查看广告效果

添加完代码之后,过几分钟再查看网站可以看到,每一篇文章后面都添加了我们想要的谷歌adsense广告单元。

有时候,可能因为缓存、广告代码生效等原因,网站内容不会立即生效,耐心等待就可以看到效果。

最后总结

如果你的网站已经有了很多篇文章,而且是后面才想添加谷歌adsense广告代码,用这个方法就可以批量的给文章底部添加,而不用一篇篇的添加,方便快捷高效!

方法思路扩展,用这种方法,我们只要更改代码content里面的内容即可,可以改成任意我们想自定义展示的内容,比如版权申明、图片广告、点赞、打赏等等:

//所有文章底部添加谷歌广告

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');

wordpress调用特定文章列表的技巧分享

在 wordpress主题制作开发 中经常会需要在特定的页面中调用出指定的文章或文章列表,接下来教大家如何调用出 wordpress文章列表 。

调用网站最新文章:

<?php
query_posts(\'showposts=10&orderby=new\'); //showposts=10表示10篇
while(have_posts()): the_post();
?>
<li><a href=\"<?php the_permalink(); ?>\"target=\"_blank\"><?php the_title() ?></a></li> //这里可以写成你自己需要的样式
<?php endwhile; ?>

调用随机文章:

<?php
query_posts(\'showposts=10&orderby=rand\'); //showposts=10表示10篇
while(have_posts()): the_post();
?>
<li><a href=\"<?php the_permalink(); ?>\"target=\"_blank\"><?php the_title() ?></a></li> //这里可以写成你自己需要的样式
<?php endwhile; ?>

调用某个分类下的最新文章:

<?php
query_posts(\'showposts=10&cat=1\'); //cat=1为调用ID为1的分类下文章
while(have_posts()) : the_post(); ?>
<li><a href=\"<?php the_permalink() ?>\"title=\"<?php the_title(); ?>\"><?php the_title(); ?></a></li>
<?php endwhile; ?>

排除某个分类下的文章:

<?php
query_posts(\'showposts=10&cat=-1\'); //cat=-1为排除ID为1的分类下文章
while(have_posts()) : the_post(); ?>
<li><a href=\"<?php the_permalink() ?>\"title=\"<?php the_title(); ?>\"><?php the_title(); ?></a></li>
<?php endwhile; ?>

以上就是文章列表的调用方法,可以将例子中的代码结合起来达到你需要的效果。

wordpress调用特定文章列表的技巧分享 (https://www.wpmee.com/) WordPress使用教程 第1张

标签:

提交需求或反馈

Demand feedback