使用gettext钩子更改Woocommerce中的一些字符串和子字符串



我多年来使用的代码(下面的示例)暂时不起作用。尝试了一些其他的代码张贴在这里,但没有快乐。看来WC已经改变了过滤/翻译的方式,每个更改的文本都需要分开。对吗?最初使用此代码有11个文本更改…

将欣赏一些代码来执行文本更改在WC 5.0谢谢!

add_filter('gettext', 'translate_text');
add_filter('ngettext', 'translate_text');
function translate_text($translated) {
$translated = str_ireplace('Products', 'Prints', $translated);
$translated = str_ireplace('Product', 'Print', $translated);
$translated = str_ireplace('Product Categories', 'Prints', $translated);
return $translated;
}

WordPress钩子gettextngettext没有改变,因为一段时间和工作可翻译的字符串,工作独立于WooCommerce版本

使其与gettextngettext钩子一起工作的正确方法是(简化一点并添加一些缺失的函数参数):

add_filter( 'gettext', 'change_some_woocommerce_strings', 10, 3 );
add_filter( 'ngettext', 'change_some_woocommerce_strings', 10, 3 );
function change_some_woocommerce_strings( $translate_text, $original_text, $domain ) {
if ( stripos( $original_text, 'Product') !== false || stripos( $original_text, 'Categories') !== false ) {
$translate_text = str_ireplace( 
array('Product categories', 'Products', 'Product'),
array('Prints', 'Prints', 'Print'), 
$original_text );
}
return $translate_text;
}

如果一些字符串没有被翻译,可能是因为它们添加了一些上下文。在这种情况下,钩子gettext_with_context是必需的,如:

add_filter( 'gettext_with_context', 'change_some_woocommerce_strings_with_context', 10, 4 );
function change_some_woocommerce_strings_with_context( $translate_text, $original_text, $context, $domain ) {
if ( stripos( $original_text, 'Product') !== false || stripos( $original_text, 'Categories') !== false ) {
$translate_text = str_ireplace( 
array('Product categories', 'Products', 'Product'),
array('Prints', 'Prints', 'Print'), 
$original_text );
}
return $translate_text;
}

代码放在活动子主题(或活动主题)的functions.php文件中。

这是最后为我工作的代码。将2 ibc更改为您想要的名称,或者就保留它。不要忘记更改您希望使用的名称,而不是Print(s)

add_filter( 'gettext', 'ibc_translate_woocommerce_strings', 999, 3 );
function ibc_translate_woocommerce_strings( $translated, $untranslated, $domain ) {
if ( ! is_admin() && 'woocommerce' === $domain ) {
switch ( $translated ) {
case 'Products':
$translated = 'Prints';
break;
case 'Product':
$translated = 'Print';
break;
case 'Product Categories':
$translated = 'Print';
break;
// ETC

}
}   
return $translated;
}

也许这也有帮助。在进行测试时,应该清空购物车,然后再刷新页面查看更改。至少这是它是如何为我工作的迷你推车小部件。祝大家成功!

最新更新