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

WordPress中PHP替换单引号致Alpine JS异常问题排查

WordPress:Timber/Twig+ACF/LazyBlocks渲染AlpineJS时单引号被替换为弯引号

问题现象

在使用Timber/Twig搭配ACF或LazyBlocks的WordPress站点中,AlpineJS组件内的单引号会被错误替换为弯引号(‘’),且仅当组件代码里包含>字符时触发。不在AlpineJS组件内的代码无此问题,替换>为其他内容后恢复正常。

测试代码

<?php
 $foo = 'bar';
?>

<div x-data="{  
    foo: '<?php echo $foo ; ?>', 
    init(){
        console.log(this.foo)
        console.log('>')
    }   
}">
   <p x-text="foo"></p>
</div>

异常输出(页面源码)

<div x-data="{  
    foo: 'bar', 
    init(){
        console.log(this.foo)
        console.log('>&amp;#8216;)
    }   
}&amp;#8221;">
   <p x-text="foo"></p>
</div></div>

浏览器检查器显示

<div x-data="{  
    foo: 'bar', 
    init(){
        console.log(this.foo)
        console.log('>‘)
    }   
}”>
   <p x-text=" foo"=""><p></p>
</div>

原因分析

这是WordPress内置的wptexturize函数导致的,该函数会自动将直引号替换为弯引号以优化排版。ACF或LazyBlocks在渲染块内容时,会对块应用the_content过滤器,而wptexturize是这个过滤器的默认回调之一,当内容中出现>这类特殊字符时,触发了错误的字符替换逻辑。

解决方法

1. 禁用块内容的wptexturize过滤

在主题的functions.php中添加以下代码,阻止ACF/LazyBlocks渲染时应用文本格式化:

// 针对ACF文本域/富文本域
add_filter('acf/render_field/type=textarea', function() {
    remove_filter('the_content', 'wptexturize');
}, 10);

add_filter('acf/render_field/type=wysiwyg', function() {
    remove_filter('the_content', 'wptexturize');
}, 10);

// 针对LazyBlocks
add_filter('lazyblocks/render_block_content', function($content) {
    remove_filter('the_content', 'wptexturize');
    return $content;
}, 1);

2. 临时禁用过滤后输出代码

在输出AlpineJS代码的PHP片段中,临时关闭wptexturize,输出后再恢复:

<?php
// 临时禁用wptexturize
remove_filter('the_content', 'wptexturize');
?>
<div x-data="{  
    foo: '<?php echo esc_js($foo); ?>', 
    init(){
        console.log(this.foo)
        console.log('>')
    }   
}">
   <p x-text="foo"></p>
</div>
<?php
// 恢复过滤
add_filter('the_content', 'wptexturize');
?>

这里用esc_js替代直接echo,确保变量安全输出到JS环境。

3. 使用Timber Twig的raw过滤器

如果用Twig模板渲染,直接用raw过滤器阻止Twig和WordPress的自动格式化:

{% filter raw %}
<div x-data="{  
    foo: '{{ foo|e('js') }}', 
    init(){
        console.log(this.foo)
        console.log('>')
    }   
}">
   <p x-text="foo"></p>
</div>
{% endfilter %}

e('js')用于安全转义JS变量,避免XSS风险。

4. 检查编辑器设置

如果是在WordPress后台编辑块模板(比如LazyBlocks的代码编辑器),确保切换到代码模式编辑,避免可视化编辑器自动替换字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:58:58