Change a specific word from a translated string using gettext filter

1.2k views Asked by At

I need to change a specific word from a translated string with variables. I'm using Spanish version of WooCommerce and don't know the exact way as it appears in the english version... but I assume, that it's not relevant to get the point.

I tried using using this kind of code snippet that works fine for a long time:

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 );

On WooCommerce when adding to cart a product that is exceeding the available quantity, you get the message (in spanish): "No puedes añadir esa cantidad al carrito - tenemos 9 existencias y has añadido 9 en tu carrito." (I suppose that in english is something like: "You cannot add that quantity to the cart - we have 9 in stock and you have added 9 to your cart."), where "9" is variable... and that's why I couldn't translate all the string using the gettext filter hook.

I am trying to change the word "existencias" by the string "unidades en stock".

Any idea please?

1

There are 1 answers

4
LoicTheAztec On

Try the following instead using strpos() and str_replace() php functions:

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;
}

It could work.

For info the sentence to translate is located here in WC_Cart add_to_cart method on line 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 ) )

Related: How do I check if a string contains a specific word?