WooCommerce订阅插件gettext过滤器翻译失效问题求助
问题排查与修复
核心问题
你要翻译的文本使用了带上下文的翻译函数 esc_html_x(),这类函数对应的过滤器不是你用的gettext,而是gettext_with_context——这就是原代码不生效的根本原因。
esc_html_x( 'Next payment', 'table heading', 'woocommerce-subscriptions' ) 中的第二个参数'table heading'是翻译上下文,普通的gettext过滤器不会处理带上下文的翻译请求。
修复后的代码
替换原代码为以下内容,即可正确捕获并翻译目标文本:
function customize_gettext_with_context( $translated, $untranslated, $context, $domain ) { // 同时匹配文本、上下文和域名,避免误翻译其他地方的内容 if ( 'Next payment' === $untranslated && 'table heading' === $context && 'woocommerce-subscriptions' === $domain ) { $translated = '你的自定义翻译文本'; // 替换成你需要的内容 } return $translated; } add_filter( 'gettext_with_context', 'customize_gettext_with_context', 97, 4 );
关键说明
- 钩子改为
gettext_with_context:该钩子专门处理_x()、esc_html_x()这类带上下文的翻译函数请求 - 过滤器参数增加到4个:必须声明完整的4个参数(
$translated,$untranslated,$context,$domain),否则无法正确匹配上下文和域名 - 增加多条件判断:同时校验原文本、上下文和插件域名,避免意外修改其他场景下相同文本的翻译
内容的提问来源于stack exchange,提问作者social.reza
相关产品推荐
相关产品推荐

