You need to enable JavaScript to run this app. WordPress PHP函数改造:条件满足时将特色图像附加至首个h2-h5标题后
优惠活动
大模型
产品
解决方案
定价
更多

WordPress PHP函数改造:条件满足时将特色图像附加至首个h2-h5标题后

WordPress 文章特色图自动插入功能扩展实现

原有add_thumb_after_h2函数的逻辑仅针对h2标签做匹配,现在需要实现的目标为:

  • 单篇文章页面下,统计h2、h3、h4、h5四类标题的总出现数量
  • 当总数量大于3时,将文章特色图像插入到内容中第一个出现的任意层级标题的闭合标签之后,不受具体标题等级限制

之前尝试的多标签计数写法失效的原因:substr_count仅能匹配传入的完整连续字符串,直接拼接<h2>,<h3>,<h4>,<h5>这类带逗号的多标签字符串,本质是在查找一段不存在的连续文本,计数结果永远为0,完全达不到多标签统计的要求。

完整可运行实现代码

// 补充原生不存在的单次替换工具函数,避免调用报错
if ( ! function_exists( 'str_replace_once' ) ) {
    function str_replace_once( $search, $replace, $content ) {
        $pos = strpos( $content, $search );
        if ( $pos === false ) {
            return $content;
        }
        return substr_replace( $content, $replace, $pos, strlen( $search ) );
    }
}

function add_thumb_after_h2( $content ) {
    // 保留原有单页判断逻辑,非单页直接返回内容
    if ( ! is_single() ) {
        return $content;
    }

    global $post;
    // 定义需要匹配的标题类型,后续调整范围只需修改这个数组
    $target_headings = [ 'h2', 'h3', 'h4', 'h5' ];
    $total_heading_count = 0;

    // 累加统计所有目标标题的总出现次数
    foreach ( $target_headings as $tag ) {
        $total_heading_count += substr_count( $content, "<{$tag}>" );
    }

    // 不满足触发条件直接返回原内容
    if ( $total_heading_count <= 3 ) {
        return $content;
    }

    // 构造特色图HTML,保留原有的DOM结构
    $thumb_html = '<div id="post_thumbnail">' . get_the_post_thumbnail( $post->ID, 'fullsize' ) . '</div>';

    // 定位内容中最早出现的目标闭合标签
    $earliest_pos = strlen( $content );
    $matched_close_tag = '';
    foreach ( $target_headings as $tag ) {
        $close_tag = "</{$tag}>";
        $pos = strpos( $content, $close_tag );
        // 记录位置最靠前的闭合标签
        if ( $pos !== false && $pos < $earliest_pos ) {
            $earliest_pos = $pos;
            $matched_close_tag = $close_tag;
        }
    }

    // 找到匹配标签后,在其后方插入特色图
    if ( $matched_close_tag ) {
        $content = str_replace_once( $matched_close_tag, $matched_close_tag . $thumb_html, $content );
    }

    return $content;
}

实现说明

  • 整个逻辑保留了原有函数的触发判断、特色图输出结构、单次替换的行为,不会破坏已生效的原有功能
  • 匹配范围由独立数组控制,后续需要增减匹配的标题类型(比如加上h1或h6),只需要修改$target_headings数组即可,无需调整核心判断逻辑
  • 插入位置通过遍历所有目标标签的闭合标签,找到内容中位置最靠前的匹配项实现,不管第一个出现的标题是h2还是h5,都能正确将特色图插到它后面

可选增强:兼容带属性的标题标签

如果日常写文章时经常给标题加自定义属性(比如<h2 class="article-subtitle">),上面的纯字符串匹配会失效,此时可以将计数和位置匹配的逻辑替换为正则实现,兼容带任意属性的标题标签:

// 统计所有带任意属性的h2-h5标题总数
preg_match_all( '/<h[2-5](\s[^>]*)?>/', $content, $open_matches );
$total_heading_count = count( $open_matches[0] );

// 定位第一个出现的h2-h5闭合标签位置
preg_match( '/<\/h[2-5]>/', $content, $close_matches, PREG_OFFSET_CAPTURE );
$matched_close_tag = ! empty( $close_matches[0] ) ? $close_matches[0][0] : '';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 08:27:01