Mar19

wordpress 文章中段落间插入广告代码

wologo-h

在网上找到的方法基本也是这个了,留存备用。

//在文章内容的第12段后面插入广告
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '</pre>
<div>
//此处放广告</div>
<pre>
';
if ( is_single() && ! is_admin() && ! is_category('cat-1') ) {
// 修改 12这个段落数
return prefix_insert_after_paragraph( $ad_code, 12, $content ); }
return $content;}

// 插入广告所需的功能代码
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_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 );
}

Comments are closed.