如何在文章段落后插入广告

有时,您可能需要在文章的第N段之后插入广告(例如Google Adsense),最常用的就是第一段。常用的就是用插件了。但为了一个功能我们就去用一个插件感觉就太臃肿了。用代码能不能解决呢。当然能。而且它特简单,让我们一起看看代码。具体代码如下,将其放置在functions.php即可。

1、我们先定义如何识别p作为段落的函数,具体的代码如下

// Parent Function that makes the magic happen
function ietheme_insert_after_paragraph( $insertion, $content, $paragraph_id = 1, $middle = false ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
if ( $middle == true ) {
$paragraph_id = round(count($paragraphs)/2);
}
if ( $paragraph_id < 1 ) {
$content = $insertion . $content;
} else if ( $paragraph_id >= count($paragraphs)  ) {
$content = $content . $insertion;
} else {
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
$content = implode( '', $paragraphs );
}
return $content;
}

2、下面是插入广告的代码

// Insert ads after first paragraph of single post content.
add_filter( 'the_content', 'ietheme_insert_post_ads' );
function ietheme_insert_post_ads( $content ) {
  $ad_code = 'Your Ads Code Here';
  if ( is_single() && ! is_admin() ) {
    return ietheme_insert_after_paragraph( $ad_code, 1, $content );
  }
  return $content;
}

是不是很简单,你需要改的就是把上面第三行的广告代码替换成自己的,第五行的1代码第一段后,如果是2就代码第二段后,依次类推。(注意:如果您的文章段落没有两段,而不设置了2,则会显示在文章末尾)。

本文已在Ie主题99839发布

文章来源:https://ietheme.com/insert-ads-in-your-post.html


撰写评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

加入我们

注册完成!

密码重置

请输入您的邮箱地址。 您将收到一个链接来创建新密码。

检查你的邮件中的确认链接。