php - 使用 gettext 过滤器从翻译的字符串中更改特定单词
问题描述
我需要从带有变量的翻译字符串中更改特定单词。我正在使用西班牙语版本的 WooCommerce,并且不知道它在英文版中出现的确切方式......但我认为,这与理解这一点无关。
我尝试使用这种可以长时间正常工作的代码片段:
function my_text_strings( $translated_text, $text, $domain ) {
switch ( $translated_text )
case 'Sample' :
$translated_text = __( 'Example!' );
break;}
return $translated_text;
}
add_filter( 'gettext', 'my_text_strings', 20, 3 );
在 WooCommerce 上,当将超过可用数量的产品添加到购物车时,您会收到消息(西班牙语):“No puedes añadir esa cantidad al carrito - tenemos 9 existencias y has añadido 9 en tu carrito。” (我想在英语中是这样的:“你不能将该数量添加到购物车 - 我们有 9 个库存,你已将 9 个添加到您的购物车。”),其中“9”是可变的......这就是为什么我无法使用gettext
过滤器挂钩翻译所有字符串。
我正在尝试通过字符串"unidades en stock"更改"existencias"一词。
请问有什么想法吗?
解决方案
尝试以下使用strpos()
和str_replace()
php 函数:
add_filter( 'gettext', 'change_add_to_cart_not_enough_stock_message', 10, 3 );
add_filter( 'ngettext', 'change_add_to_cart_not_enough_stock_message', 10, 3 );
function change_add_to_cart_not_enough_stock_message( $translated_text, $text, $domain ) {
// Singular (I don't know if this one will work)
if ( strpos( $translated_text, 'existencia y has añadido' ) !== false ) {
$translated_text = str_replace('existencia y has añadido', 'unidad en stock y has añadido', $translated_text);
}
// Plural
if ( strpos( $translated_text, 'existencias y has añadido' ) !== false ) {
$translated_text = str_replace('existencias y has añadido', 'unidades en stock y has añadido', $translated_text);
}
return $translated_text;
}
它可以工作。
有关信息,要翻译的句子位于在线WC_Cart
add_to_cart
方法中1203
:
sprintf( __( 'You cannot add that amount to the cart — we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $product_data->get_stock_quantity(), $product_data ), wc_format_stock_quantity_for_display( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ], $product_data ) )
推荐阅读
- javascript - 如何从 React Js 中的组件获取父文件中的输入文本框值
- python - 在 Tensorflow 中向量化乘法
- javascript - 将按钮的焦点设置为通过键盘选择时替换它的按钮
- c# - 如何使图像在 Properties.Resources 中可用
- android - 让房间处理带有@Embedded 和@Relation 注释的对象的@Insert
- android - SQLITE 数据库不更新表
- here-api - 验证 [here-rest] 无法正常工作
- java - 如何发出 Java HTTP 异步请求?
- c# - 仅增加字符串字母和数字c#
- excel - 受保护工作簿的 VBA Excel 拼写检查