有些我們可能考慮到推廣內(nèi)容或者廣告客戶的需要,希望在原來(lái)所有的WordPress網(wǎng)站某個(gè)斷后后面添加內(nèi)容模塊的,這里當(dāng)然可以使用插件實(shí)現(xiàn)的,但是如果不用插件是否可以實(shí)現(xiàn)呢?
廢話不多說(shuō),直接上代碼。
// 在文章內(nèi)容插入代碼 - http://bjj.org.cn/wpinsert-post.html
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads($content){
$pattern = "/<p>.*?<\/p>/";
$paragraph_count = preg_match_all($pattern,$content); //計(jì)算文章的段落數(shù)量
if($paragraph_count >= 4 && is_single()){//如果文章的段落數(shù)量少于4段,則不會(huì)插入文章段落廣告
$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 );
}
默認(rèn)是第二段后面,我們有需要也可以修改。當(dāng)然也希望文章稍微長(zhǎng)一些才添加,比如超過四段。
是不是很帥?比如我們可以插入隨機(jī)的廣告或者是插入一些推廣的引導(dǎo)CPS。
評(píng)論