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

WordPress中使用esc_html__()输出带变量字符串失效问题咨询

WordPress esc_html__() 变量不替换问题修复

问题根因

esc_html__() 是WordPress内置的国际化转义函数,官方仅定义了两个入参:

  • 第一个参数:待翻译、待转义的原始字符串
  • 第二个参数:对应主题/插件的文本域

你传入的第三个参数$reserve_price 不属于该函数的可识别参数,无法自动替换字符串中的%s占位符,因此出现变量不生效的问题。

修复方案

占位符替换需要借助PHP原生的sprintf() 函数实现,同时为了符合安全规范,动态输出的$reserve_price 也需要做HTML转义处理。

修改后的代码如下:

<?php
global  $product, $post;
$posts_id = $product->get_id(); 
$reserve_price = get_post_meta($posts_id, '_auction_reserved_price', true);

if ($product->is_reserved() === true && $product->is_reserve_met() === false) : ?>

<p class="reserve hold"  data-auction-id="<?php echo esc_attr( $product->get_id() ); ?>">
    <?php echo apply_filters('reserve_bid_text', sprintf( esc_html__('Reserve price has not been met, needed to enter $ %s or more', 'wc_simple_auctions'), esc_html($reserve_price) )); ?>
</p>

<?php endif; ?>

逻辑说明

  • 先通过esc_html__() 完成原始字符串的翻译和HTML转义,避免翻译内容中存在恶意代码
  • 再通过sprintf() 将转义后的$reserve_price 替换到%s的对应位置
  • 额外给$reserve_price 添加esc_html() 转义,避免自定义字段存储的异常内容导致前端安全问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 06:57:01