Polylang翻译function.php自定义字符串时丢失HTML结构问题咨询
Polylang翻译WooCommerce自定义内容时HTML结构错位问题
问题背景
此前参考本站相关主题的建议但未找到对应解决方案,Polylang的运行逻辑较为复杂,可能存在遗漏配置点。在WooCommerce结账页添加了投票功能,功能本身运行正常,翻译功能也可生效,但出现翻译内容与HTML结构错位的问题。
问题表现
Polylang翻译时会忽略HTML结构,将翻译后的字符串抛出对应div、H2标签外,推测后续label标签的翻译也会出现相同问题,尝试过基于echo的调整方案但未生效,希望获得相关解决思路。
相关代码
functions.php 自定义代码
add_action('init', function() { pll_register_string('thankyou', 'What do you think about the shop?'); pll_register_string('OceanWP', 'Superb'); }); add_action( 'woocommerce_thankyou', 'thank_poll_form', 10 ); function thank_poll_form( $order_id ) { echo '<div class="thank-you-poll"><h2>'.pll_e('What do you think about the shop?').'</h2> <form id="thankyou_form"> <label><input type="radio" name="like" value="superb"> Superb</label> <label><input type="radio" name="like" value="good enough"> Good enough</label> <label><input type="radio" name="like" value="could be better"> Could be better</label> <input type="hidden" name="action" value="collect_feedback" /> <input type="hidden" name="order_id" value="' . $order_id . '" /> ' . wp_nonce_field( 'thankyou'.$order_id, 'thankyou_nonce', true, false ) . ' </form></div>'; }
实际渲染的HTML代码
Was hälst du von unserem Shop? <div class="thank-you-poll"><h2></h2> <form id="thankyou_form"> <label><input type="radio" name="like" value="superb"> Superb</label> <label><input type="radio" name="like" value="good enough"> Good enough</label> <label><input type="radio" name="like" value="could be better"> Could be better</label> <input type="hidden" name="action" value="collect_feedback"> <input type="hidden" name="order_id" value="4418"> <input type="hidden" id="thankyou_nonce" name="thankyou_nonce" value="7624232590"><input type="hidden" name="_wp_http_referer" value="/de/kasse/order-received/4418/?key=wc_order_fKU39RE1qr0iI&utm_nooverride=1"> </form></div>
问题原因与解决方案
原因
问题出在pll_e函数的特性上:pll_e会直接输出翻译后的字符串,不需要再嵌套在echo语句中。将pll_e放在echo的字符串拼接逻辑里时,pll_e会先执行输出翻译内容,之后echo才会输出剩余的HTML结构,自然就出现了翻译内容跑到H2标签外的情况。
解决方案
将pll_e替换为pll__即可。pll__的作用是返回翻译后的字符串,不会直接输出,刚好适合用来做字符串拼接后统一输出。
补充说明:如果之前使用pll__触发过致命错误,优先排查是否存在拼写错误、Polylang插件未正常启用的问题,该函数本身属于Polylang官方提供的标准函数。
参考经验
该调整方案已经过实测有效,遇到同类Polylang翻译内容错位问题的用户可优先检查翻译函数的使用场景是否匹配。
内容的提问来源于stack exchange,提问作者Mike8040
相关产品推荐
相关产品推荐

