WordPress 如何在文章段落后添加自定义内容

如果想在 WordPress 文章段落后添加自定义内容,比如在文章第二段后添加广告,可以尝试用下面的代码:

  1. // 在文章第二段之后插入内容
  2. add_filter( 'the_content', 'prefix_insert_post_ads' );
  3. function prefix_insert_post_ads( $content ) {
  4. $ad_code = '<div>添加的文字</div>';
  5. if ( is_single() && ! is_admin() ) {
  6. return prefix_insert_after_paragraph( $ad_code, 2, $content );
  7. }
  8. return $content;
  9. }
  10. // 主要函数
  11. function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  12. $closing_p = '</p>';
  13. $paragraphs = explode( $closing_p, $content );
  14. foreach ($paragraphs as $index => $paragraph) {
  15. if ( trim( $paragraph ) ) {
  16. $paragraphs[$index] .= $closing_p;
  17. }
  18. if ( $paragraph_id == $index + 1 ) {
  19. $paragraphs[$index] .= $insertion;
  20. }
  21. }
  22. return implode( '', $paragraphs );
  23. }

分别在段落 2、4、6 后面添加不同的内容

  1. add_filter( 'the_content', 'add_ads_to_content' );
  2. function add_ads_to_content( $content ) {
  3. $ads = array(
  4. 2 => 'ad code 1', // paragraph_id => ad_code
  5. 4 => 'ad code 2', // paragraph_id => ad_code
  6. 6 => 'ad code 3' // paragraph_id => ad_code
  7. );
  8. if ( is_single() && ! is_admin() ) {
  9. foreach ($ads as $paragraph_id => $ad_code) {
  10. $content = prefix_insert_after_paragraph( $ad_code, $paragraph_id, $content );
  11. }
  12. }
  13. return $content;
  14. }
  15. function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  16. $closing_p = '</p>';
  17. $paragraphs = explode( $closing_p, $content );
  18. foreach ($paragraphs as $index => $paragraph) {
  19. if ( trim( $paragraph ) ) {
  20. $paragraphs[$index] .= $closing_p;
  21. }
  22. if ( $paragraph_id == $index + 1 ) {
  23. $paragraphs[$index] .= $insertion;
  24. }
  25. }
  26. return implode( '', $paragraphs );
  27. }

如果只显示在某个分类文章中添加,也可以这么写

  1. add_filter( 'the_content', 'prefix_insert_post_ads' );
  2. function prefix_insert_post_ads( $content ) {
  3. $ad_code = '<div>自定义文字</div>';
  4. if ( is_single() && ! is_admin() && in_category('29') ) {
  5. return prefix_insert_after_paragraph( $ad_code, $content );
  6. }
  7. return $content;
  8. }
  9. function prefix_insert_after_paragraph( $insertion, $content ) {
  10. $closing_p = '</p>';
  11. $paragraphs = explode( $closing_p, $content );
  12. $paragraph_id = round(count($paragraphs) / 2);
  13. foreach ($paragraphs as $index => $paragraph) {
  14. if ( trim( $paragraph ) ) {
  15. $paragraphs[$index] .= $closing_p;
  16. }
  17. if ( $paragraph_id == $index + 1 ) {
  18. $paragraphs[$index] .= $insertion;
  19. }
  20. }
  21. return implode( '', $paragraphs );
  22. }

给TA打赏
共{{data.count}}人
人已打赏
WordPress教程

WordPress 去掉菜单项链接A标签

2022-9-21 17:04:13

WordPress教程

WordPress 如何在一定字数之后添加自定义内容

2022-10-3 20:02:31

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索