[WordPress教程]在wordpress文章里面随机段落中插入任意广告

1.首先在主题functions.php里面插入功能代码

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

2.插入广告代码,请更换代码中广告为你自己的

// wordpress文章里面随机段落中插入任意广告
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;
}

  • 发表评论