AI摘要

本文介绍了一种在WordPress文章段落中随机显示广告的方法,只需将提供的代码插入主题的functions.php文件,即可在不少于8个段落的文章中自动随机插入广告,同时建议有能力的用户将广告代码集成至主题后台设置以便于修改。

很多 WordPress 主题都自带了广告位,但是大部分主题是不支持在正文中插入广告的,今天分享一个在 WordPress 文章段落中随机位置显示广告的方法。

在 WordPress 文章段落中随机位置显示广告的方法不是很复杂,这里有现成的代码,你需要把以下代码插入你主题的 functions.php 中即可(注意:将你的广告代码替换为你的广告内容)。

随机显示广告代码:

[hidecontent type="reply"]

add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads($content){
 $pattern = "/<p>.*?<\/p>/";
 $paragraph_count = preg_match_all($pattern,$content); //计算文章的段落数量

 if($paragraph_count >= 8 && is_single()){ // 如果文章的段落数量少于 8 段,则不会插入文章段落广告
 $paragraph_count -=2;
 $insert_paragraph=rand(3,$paragraph_count);
 $ad_code = '<div>你的广告代码</div>';
 return prefix_insert_after_paragraph( $ad_code, $insert_paragraph, $content );
 }
 return $content;
}

// 插入广告所需的功能代码
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 );
}
[/hidecontent]

如果你动手能力比较强,你可以研究研究把需要替换广告代码位置写入主题的设置里面,以后就不用再修改源代码了,直接在后台修改广告代码,但是由于每个主题的设置代码不同,我这里就不多说了。

Zibll主题设置 >> 全局&功能 >> 自定义代码 >> 自定义javascript代码