目前,我已经建立了我的网站,该网站会在任何文章的第二段之后自动添加Google Adsense广告,但是如果有人可以提供帮助,我希望对此进行改进.
我想在此代码中添加另外2条广告;一个在第六段之后,另一个在第十段之后.如果文章没有达到这些段落编号,则不应显示广告.
这可能确实很明显,但是我尝试过的任何操作都导致当我重新加载网站时functions.PHP文件崩溃.
我的代码是…
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div class="mobilead .visible-xs-block hidden-sm hidden-md hidden-lg"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-XXXX"
data-ad-slot="1716361890"
data-ad-format="auto"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
作为补充问题-是否有一种方法可以将这些广告限制为仅在帖子而非页面上展示?目前,他们正在任何地方显示.
任何帮助将不胜感激.
解决方法:
您的广告代码有太多错误,无法尝试猜测它应该是什么(它的开头是< div>但没有结尾的< / div> ;,它似乎是javascript之外的< script>标签)
…所以我跳过了这一部分,仅演示了如何插入另一段-这将在您想要的位置插入一些内容,并还显示了如何使用get_post_type()确保广告仅显示在帖子上:
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
//The last condition here ensures that ads are only added to posts
if ( is_single() && !is_admin() && get_post_type() === 'post' ) {
return prefix_insert_ads( $content );
}
return $content;
}
function prefix_insert_ads( $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
$paragraphs[$index] .= $closing_p;
if ( in_array($index, array(1, 5, 9)) ) {
//Replace the html here with a valid version of your ad code
$paragraphs[$index] .= '<p style="background:#f00">Ad goes here</p>';
}
}
return implode( '', $paragraphs );
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。