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
相关产品推荐
相关产品推荐

