修改PHP代码:让广告从第5段后开始每5段插入一次
修改PHP代码实现从第5段后开始每5段插入广告
原代码的问题出在段落插入的判断逻辑上:数组索引从0开始,$index % $paragraph_id === 0会匹配索引0、5、10...对应的段落,也就是第1、6、11段之后插入广告。要实现从第5段后开始,每5段插入一次,只需要调整判断条件,让它仅在段落数为5的倍数时触发插入(即第5、10、15段之后)。
修改后的完整代码如下:
// 在每第5段之后插入广告(从第5段开始) add_filter( 'the_content', 'prefix_insert_post_ads' ); function prefix_insert_post_ads( $content ) { $ad_code = '<center>AD CODE</center>'; if ( is_single() && ! is_admin() ) { return prefix_insert_after_paragraph( $ad_code, 5, $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; } // 修改判断条件:仅当段落数是5的倍数时插入(索引+1等于5的倍数) if ( ($index + 1) % $paragraph_id === 0 ) { $paragraphs[$index] .= $insertion; } } return implode( '', $paragraphs ); }
关键修改说明
把原代码中的判断条件:
if ( $index % $paragraph_id === 0 ) {
替换为:
if ( ($index + 1) % $paragraph_id === 0 ) {
因为数组索引从0开始,$index +1对应实际的段落序号,当这个值是5的倍数时,就代表当前是第5、10、15...段,在这些段落之后插入广告,正好符合需求。
内容的提问来源于stack exchange,提问作者Komolafe Olumide
相关产品推荐
相关产品推荐

