You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现每隔指定字数与段落重复插入WordPress文中广告

循环插入文中广告PHP代码修改方案

原代码核心问题:

  1. 固定了$max_ads = 2的硬限制,达到次数后就停止插入
  2. 没有段落计数逻辑,仅支持字数单一判断
  3. 没有循环重置计数器的逻辑,无法重复触发插入

修改后的完整代码:

function anunciamentosegundo($content) {
    $ad_code = '<script type="application/javascript">Adsense code goes here</script>';
    
    // 可配置参数
    $enable_min_length = 1800; // 文章长度超过该值才开启广告插入
    $ad_interval_words = 250; // 每隔多少字检查一次广告插入
    $ad_interval_paragraphs = 4; // 每隔多少个段落检查一次广告插入
    $max_ads_total = 10; // 全局最多插入广告数,可根据需求调整,避免广告过密
    $insert_position_offset = 0; // 插入广告后的内容偏移量修正
    
    $content_length = strlen($content);
    if ($content_length <= $enable_min_length) {
        return $content;
    }
    
    $current_word_count = 0;
    $current_paragraph_count = 0;
    $in_tag = false;
    $inserted_ads = 0;
    
    for ($i = 0; $i < $content_length; $i++) {
        // 跳过HTML标签内部内容
        if ($content[$i] == '<') {
            $in_tag = true;
        } elseif ($content[$i] == '>') {
            $in_tag = false;
            // 检测到段落结束标签,段落计数+1
            if (substr($content, $i - 3, 4) == '</p>') {
                $current_paragraph_count++;
            }
            continue;
        }
        
        if (!$in_tag && ctype_space($content[$i])) {
            $current_word_count++;
        }
        
        // 同时满足字数阈值、段落阈值、未达最大广告数,执行插入
        if ($current_word_count >= $ad_interval_words 
            && $current_paragraph_count >= $ad_interval_paragraphs 
            && $inserted_ads < $max_ads_total
        ) {
            // 找到当前位置后的第一个</p>标签后插入
            $p_end_pos = strpos($content, '</p>', $i);
            if ($p_end_pos === false) {
                break;
            }
            $insert_pos = $p_end_pos + 4 + $insert_position_offset;
            
            // 插入广告
            $content = substr_replace($content, $ad_code, $insert_pos, 0);
            $inserted_ads++;
            
            // 修正偏移量,重置计数器
            $insert_position_offset += strlen($ad_code);
            $current_word_count = 0;
            $current_paragraph_count = 0;
            $i = $p_end_pos; // 跳转至段落结束位置继续遍历
        }
    }
    
    return $content;
}
add_filter( 'the_content', 'anunciamentosegundo' );

参数调整说明:

  • 可根据实际需求调整$ad_interval_words(间隔字数)、$ad_interval_paragraphs(间隔段落数)的数值,实现不同的插入密度
  • $max_ads_total可以根据文章长度的常见范围设置合理值,避免页面广告过多影响体验
  • 若不需要段落阈值,直接将$ad_interval_paragraphs设为0即可,若不需要字数阈值则将$ad_interval_words设为0

内容的提问来源于stack exchange,提问作者Brave Warrior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:27:04