Translate or replace text in WordPress via functions.php

You may want to translate or change some text on your WordPress site but you don’t want to mess around with string translations or editing the PO/MO files. Luckily there is an alternative way to do this. Quick and easy. All you have to do is add the code below in the functions.php file of your child theme. Keep in mind that this only works with translatable text that is being used inside __() or _e() functions.

The code below makes use of the gettext filter. Replace Old Text with the text you want to replace. This is case sensitive so type it exactly as you see it on your website. Replace New Text with your replacement text or leave it blank if you want to remove the original text.

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

You can also use this in an array() for example:

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

Thats it!

You might like this too!

Leave a Reply

Your email address will not be published. Required fields are marked *