鹿泽鹿泽  2024-07-18 15:32:36 鹿泽笔记 隐藏边栏  0 

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

// 在文章第二段之后插入内容
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
  $ad_code = '<div>添加的文字</div>';
  if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $ad_code, 2, $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 );
}

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

add_filter( 'the_content', 'add_ads_to_content' );
function add_ads_to_content( $content ) {
  $ads = array(
    2 =>  'ad code 1', // paragraph_id => ad_code
    4 => 'ad code 2', // paragraph_id => ad_code
    6 => 'ad code 3' // paragraph_id => ad_code
  );
 
  if ( is_single() && ! is_admin() ) {
    foreach ($ads as $paragraph_id => $ad_code) {
      $content = prefix_insert_after_paragraph( $ad_code, $paragraph_id, $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 );
}

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

add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
  $ad_code = '<div>自定义文字</div>';
    if ( is_single() && ! is_admin() && in_category('29') ) {
    return prefix_insert_after_paragraph( $ad_code, $content );
  }
  return $content;
}
 
 
function prefix_insert_after_paragraph( $insertion, $content ) {
  $closing_p = '</p>';
  $paragraphs = explode( $closing_p, $content );
  $paragraph_id = round(count($paragraphs) / 2);
  foreach ($paragraphs as $index => $paragraph) {
    if ( trim( $paragraph ) ) {
      $paragraphs[$index] .= $closing_p;
    }
    if ( $paragraph_id == $index + 1 ) {
    $paragraphs[$index] .= $insertion;
    }
  }
  return implode( '', $paragraphs );
}
1、文章版权归作者所有,未经允许请勿转载。
2、本站所有文章,如无特殊说明或标注,均为本站原创发布。任何在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们邮箱:526009505@qq.com进行处理。
3、咨询请联系QQ:526009505