纯代码实现WordPress文章段落中添加广告

2020年01月2日19:39:11 发表评论 热度336 ℃

WordPress中添加代码的方式很多,以前也有介绍过。参见

代码实现WordPress 在文章内容的随机段落中间插入广告

在Wordpress上手动添加广告的方法 

给首页第一篇文章上加上环绕广告

文章中添加广告-wordpress终极技巧

短代码实现在wordpress任意位置添加广告

纯代码实现WordPress文章段落中添加广告

本代码实现在指定段落添加广告,将下面的代码添加到当前主题的 functions.php

  1. /**
  2.  * WordPress 在文章内容中间插入广告
  3.  * https://www.wpdaxue.com/insert-ads-within-post-content-in-wordpress.html
  4.  */
  5. //在文章内容的第二段后面插入广告
  6. add_filter( 'the_content', 'prefix_insert_post_ads' );
  7. function prefix_insert_post_ads( $content ) {
  8.     $ad_code = '<div>添加你的广告代码</div>';
  9.     if ( is_single() && ! is_admin() ) {
  10.         // 修改 2 这个段落数
  11.         return prefix_insert_after_paragraph( $ad_code, 2, $content );
  12.     }
  13.     return $content;
  14. }
  15. // 插入广告所需的功能代码
  16. function prefix_insert_after_paragraph( $insertion$paragraph_id$content ) {
  17.     $closing_p = '</p>';
  18.     $paragraphs = explode$closing_p$content );
  19.     foreach ($paragraphs as $index => $paragraph) {
  20.         if ( trim( $paragraph ) ) {
  21.             $paragraphs[$index] .= $closing_p;
  22.         }
  23.         if ( $paragraph_id == $index + 1 ) {
  24.             $paragraphs[$index] .= $insertion;
  25.         }
  26.     }
  27.     return implode( ''$paragraphs );
  28. }

( $ad_code, 2, $content )为第二段落后添加的广告,可根据情况修改,比如在第三段落添加则为:

$ad_code, 3, $content )

瓜皮猪

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: