By adding the below code to the functions.php file or a code plugin one can easily translate text without needing to install a plugin such as Loco Translate or translating using PO and MO files.
It only works with translatable text used inside __() or _e() functions.
/* Old Text = word or words to be translated.
New Text = what it is to be translated into.
https://hoolite.be/coding/replace-or-translate-text-in-wordpress-via-functions-php/ */
function change_translate_text( $translated_text ) {
if ( 'Old Text' === $translated_text ) {
$translated_text = 'New Text!';
}
return $translated_text;
}
add_filter( 'gettext', 'change_translate_text', 20 );
To translate multiple text.
function multi_change_translate_text( $translated ) {
$text = array(
'Old Text 1' => 'New Text 1',
'Old Text 2' => 'New Text 2',
'Old Text 3' => 'New Text 3',
);
$translated = str_ireplace( array_keys( $text ), $text, $translated );
return $translated;
}
add_filter( 'gettext', 'multi_change_translate_text', 20 );
Resources:
https://hoolite.be/coding/replace-or-translate-text-in-wordpress-via-functions-php/
https://www.businessbloomer.com/translate-single-string-woocommerce-wordpress/