Translate WordPress string with code

Author: Aleš Sýkora, 21. 1. 2021

Sometimes you want to change just one word in translation and you dont want to create .po and .mo files, install translation plugins etc.

So use the function str_replace and replace the string you want. For example I am changin "Add to cart" to "Přidat do košíku".

You can place this code to your code snippets, custom funcionality plugin, functions.php... It is up to you :-).

function twiki_translate_string( $translated_text, $text, $domain ) {
    $translated_text = str_replace('Add to cart', 'Přidat do košíku', $translated_text);
    return $translated_text; 
add_filter( 'gettext', 'twiki_translate_string', 100, 3 );