首页 > 解决方案 > 使用 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"一词。

请问有什么想法吗?

标签: phpwordpresswoocommercegettextwordpress-hook

解决方案


尝试以下使用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 ) )

相关:如何检查字符串是否包含特定单词?


推荐阅读