代码实现的方式很简单,只要在下面functions.php插入下面的代码即可实现(记得将:你的广告代码替换掉)
- 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 );
- }