
本文介绍使用 gettext_woocommerce 钩子批量翻译 WooCommerce 前端界面中未被 Loco Translate 扫描到的关键字符串(如“Coupon Code”“Apply coupon”等),避免硬编码、兼容主题更新,并提供可扩展的代码实现与最佳实践。
本文介绍使用 `gettext_woocommerce` 钩子批量翻译 woocommerce 前端界面中未被 loco translate 扫描到的关键字符串(如“coupon code”“apply coupon”等),避免硬编码、兼容主题更新,并提供可扩展的代码实现与最佳实践。
在 WooCommerce 开发中,部分界面字符串(例如 "Coupon Code"、"Code here"、"Back to cart"、"Your order" 等)可能不会出现在 Loco Translate 的默认扫描结果中——这是因为它们并非通过标准 _e()/__() 函数在 WooCommerce 主插件文件中直接声明,而是由模板片段、JavaScript 渲染或动态上下文生成,导致翻译工具无法自动提取。
此时,推荐使用 WordPress 内置的上下文感知翻译钩子:gettext_{$domain}。针对 WooCommerce,其专属域名为 woocommerce,因此应使用 gettext_woocommerce 过滤器。该钩子仅作用于 WooCommerce 插件自身输出的文本(不干扰主题或核心翻译),安全、精准且性能友好。
以下是一个完整、可直接集成到子主题 functions.php 或自定义插件中的翻译示例:
add_filter('gettext_woocommerce', 'translate_woocommerce_strings');
function translate_woocommerce_strings($string) {
// 使用 switch 提升可读性与执行效率(优于多层 if)
switch ($string) {
case 'Coupon Code':
$string = 'Code promo';
break;
case 'Code here':
$string = 'Saisissez le code ici';
break;
case 'Apply coupon':
$string = 'Appliquer le code';
break;
case 'Update cart':
$string = 'Mettre à jour le panier';
break;
case 'Back to cart':
$string = 'Retour au panier';
break;
case 'Your order':
$string = 'Votre commande';
break;
case 'Related':
$string = 'Produits associés';
break;
// ✅ 可继续添加其他字符串...
}
return $string;
}
⚠️ 重要注意事项:
- 请勿在 switch 中遗漏 break,否则将引发意外的字符串级联替换;
- 此方法适用于纯文本字符串,不适用于含 HTML 标签或占位符(如 %s items)的复合字符串——后者需改用 ngettext_woocommerce 或正则匹配(慎用);
- 若同时使用 .pot 文件 + Loco Translate,建议优先通过 PO 文件翻译;gettext_woocommerce 应作为补充方案,用于动态生成或插件未导出的边缘字符串;
- 为便于维护,建议将翻译映射表单独抽离为关联数组,例如:
$translations = [ 'Coupon Code' => 'Code promo', 'Apply coupon' => 'Appliquer le code', // ... ]; return $translations[$string] ?? $string;
✅ 总结:当 Loco Translate 无法捕获 WooCommerce 字符串时,gettext_woocommerce 是最可靠、最轻量的解决方案。它精准作用于插件域、不影响全局翻译流程,且易于测试与迭代——是多语言 WooCommerce 站点不可或缺的翻译补全机制。











