PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了PHP-在设置段落数后添加其他广告大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

目前,我已经建立了我的网站,该网站会在任何文章的第二段之后自动添加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&gt ;,它似乎是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 );
}

大佬总结

以上是大佬教程为你收集整理的PHP-在设置段落数后添加其他广告全部内容,希望文章能够帮你解决PHP-在设置段落数后添加其他广告所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: