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

WordPress PHP代码嵌入促销内容不显示问题求助

WordPress文章嵌入促销内容不显示的排查与修复

核心问题分析

  1. 重复定义函数触发致命错误
    代码里重复声明了move_custom_content_in_the_main_loop函数两次,PHP不允许同名函数重复定义,这会直接导致代码执行中断,功能完全失效。必须删除其中一套重复的函数代码。

  2. 钩子优先级过早
    使用优先级1的the_content钩子,可能在Elementor等页面构建器完成内容生成前就执行了,导致获取的原始内容为空或不完整,插入操作自然无法生效。

  3. 段落拆分逻辑有漏洞
    原代码用preg_split('/<\/p>/', $content)拆分段落,会保留空元素,重构内容时容易出现标签异常,导致插入的内容被隐藏或格式混乱。

  4. 范围限制过严
    代码仅对ID为21197的单篇文章生效,如果目标文章不是这篇,自然看不到促销内容。

修复后的代码

add_filter( 'the_content', 'move_custom_content_in_the_main_loop', 20 );

function move_custom_content_in_the_main_loop( $content ) {
    // 仅在单篇文章且为主查询时执行,可根据需求修改文章ID范围
    if ( is_singular() && is_main_query() && get_the_ID() == 21197 ) {
        // 获取ACF字段值
        $acf_value = get_field( 'kies_promosie' );
        $acf_value_2 = get_field( 'kies_promosie_2' );
        $acf_value_3 = get_field( 'kies_promosie_3' );

        // 拆分段落并过滤空元素,避免无效操作
        $paragraphs = preg_split( '/<\/p>\s*/', trim( $content ) );
        $paragraphs = array_filter( $paragraphs, function( $p ) {
            return trim( $p ) !== '';
        } );
        $total_paragraphs = count( $paragraphs );
        $insertions = 0;

        if ( $total_paragraphs > 0 ) {
            // 插入25%位置的促销内容
            if ( $acf_value ) {
                $first_position = max( round( 0.25 * $total_paragraphs ) - 1 + $insertions, 0 );
                array_splice( $paragraphs, $first_position, 0, '<p>' . do_shortcode( '[elementor-template id="8471"]' ) . '</p>' );
                $insertions++;
            }

            // 插入50%位置的促销内容
            if ( $acf_value_2 ) {
                $second_position = max( round( 0.5 * $total_paragraphs ) - 1 + $insertions, 0 );
                array_splice( $paragraphs, $second_position, 0, '<p>' . do_shortcode( '[elementor-template id="16315"]' ) . '</p>' );
                $insertions++;
            }

            // 插入75%位置的促销内容
            if ( $acf_value_3 ) {
                $third_position = max( round( 0.75 * $total_paragraphs ) - 1 + $insertions, 0 );
                array_splice( $paragraphs, $third_position, 0, '<p>' . do_shortcode( '[elementor-template id="16316"]' ) . '</p>' );
            }

            // 重构内容,确保标签闭合正确
            $content = implode( '</p>' . PHP_EOL, $paragraphs ) . '</p>';
        }
    }

    return $content;
}

额外排查步骤

  • 检查服务器PHP错误日志,确认是否存在函数重复定义的报错,这是最常见的直接原因。
  • 打开目标文章(ID21197)的编辑页,验证ACF字段kies_promosie系列是否已正确设置值(勾选或填写内容)。
  • 在文章编辑器里直接插入Elementor模板短码(比如[elementor-template id="8471"]),预览看模板是否正常显示,排除模板本身的问题。
  • 如果用了Elementor这类页面构建器,尝试调整钩子优先级(比如改成30),确保内容生成完成后再执行插入。

内容的提问来源于stack exchange,提问作者Elanie Van Der Westhuizen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:05:00