Easily Translate and Replace Text in WordPress using Functions.php and the Gettext Filter

Translating, replacing or modifying text in WordPress is a common task that can be done in several ways. One of the simplest methods is by using the functions.php file. By adding a code snippet, you can change the text on your WordPress site without having to use plugins.

This tutorial will show you how to translate or replace text in WordPress using functions.php. You’ll learn how to utilize the gettext filter to modify the text on your site, including post and page titles, descriptions, and other content.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Create a Custom Function

First, access the functions.php file in your WordPress theme. You can access it through the WordPress backend editor or through a file manager on your website hosting platform.

Use the add_filter function to hook into the gettext filter. The gettext filter is a WordPress filter hook that allows developers to modify text strings that are returned by the __() and _e() translation functions. The first parameter is the name of the filter, and the second parameter is the name of the function that will run when the filter is triggered.

When the translation function is called, it first retrieves the translated string using the gettext filter. The filter allows us to modify the string before it is returned. This allows us to programmatically translate or replace text strings in our WordPress site without having to modify the underlying source code or language files.

add_filter( 'gettext', 'custom_text_replace', 20, 3 );
Code language: PHP (php)

The third parameter, 20, is the priority of the filter. The lower the number, the earlier the filter will run. The fourth parameter, 3, is the number of arguments the filter should accept.

Create the function that will run when the filter is triggered. This function should take three parameters:

  • $translated_text: This is the translated text that has already been processed by the translation functions in WordPress.
  • $untranslated_text: This is the original text string that needs to be translated. This text string has not yet been processed by the translation functions in WordPress, so you can use it to determine which text to translate.
  • $domain: This is the text domain of the text string that needs to be translated. The text domain is used to identify which translation file to use to translate the text. By using the text domain, you can ensure that the correct translation file is used for each text string in your WordPress theme or plugin.
function custom_text_replace( $translated_text, $untranslated_text, $domain ) {
    switch ( $untranslated_text ) {
        case 'Read More':
            $translated_text = __( 'Learn More', $domain );
            break;
        case 'Leave a Comment':
            $translated_text = __( 'Share Your Thoughts', $domain );
            break;
        case 'Search':
            $translated_text = __( 'Find', $domain );
            break;
        // Leave the default case out when using languages other than en_US
        default:
            $translated_text = $untranslated_text;
            break;
    }
    return $translated_text;
}
add_filter( 'gettext', 'custom_text_replace', 20, 3 );

Code language: PHP (php)

The purpose of the switch case is to check the value of $untranslated_text and modify the $translated_text accordingly. In each case, if the value of $untranslated_text matches a certain string, the $translated_text is updated with a new string using the __() function. This way, you can programmatically translate or replace the text strings in your WordPress site.

Finally, the modified $translated_text is returned by the function, which can then be used by the rest of your WordPress site.

The default case is important as it serves as a fallback for text strings that are not explicitly handled by your custom translation logic. However, it has been observed that using the default case may cause unintended behavior, such as text reverting to en_US when the WordPress language is set to a different language, like nl_NL.

To avoid this issue, we recommend not including the default case in your switch statement when using languages other than en_US.

That’s it! Using the gettext filter and switch case is a powerful and flexible way to translate or replace text in WordPress, and can help you create a website that truly reflects your brand and values. Whether you’re looking to create a more user-friendly website, or you simply want to customize your website’s text to your specific needs, this technique is a great starting point.

Leave your feedback and help us improve 🐶

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee ☕️ or donating via PayPal 💰.

More free knowledge, because why not?

33 Comments

  • Using this changes “Hi, admin” to “Howdy, admin” and “customise” to “customize” – do you know how we can use this so it does not override the en_GB language with en_US variables?

    Reply
    • I worked it out, I just removed:

      default:
      $translated_text = $untranslated_text;
      break;

      From the bottom and the override of other things stopped.

      Reply
      • Hi Simon, I’m glad it worked out!

        The default behavior of the gettext filter is to return the translated text as-is if a translation is found, and the original text if no translation is found. If you are seeing unexpected translations when using the default case in your `switch` statement, it is possible that the translation for the text you are seeing is being provided by a different translation file.

        For example, if your WordPress site is set to the `en_GB` locale, but a translation file for the `en_US` locale is being used, then any text that is not explicitly translated in your `switch` statement will be translated using the `en_US` translation file. This can result in unexpected translations for text that you did not explicitly translate.

        To avoid this issue, you can ensure that your `switch` statement includes all of the text that you want to translate, and does not rely on the default case to provide translations. Alternatively, you can make sure that your WordPress site is set to the correct locale, and that the appropriate translation files are being used. You can check your site’s locale by looking at the `WPLANG` constant in your `wp-config.php file`, and you can check which translation files are being loaded by looking at the `load_textdomain` and `load_plugin_textdomain` functions in your theme or plugin code.

        Reply
        • Just like Simon, the code workst, but the rest of the site is reverted to en_US (when nl_NL should be used).
          I added
          define (‘WPLANG’, ‘nl_NL’);
          rule in the wp-config.php, but English translations keep showing up. When I remove
          default:
          $translated_text = $untranslated_text;
          break;
          it works with the rest in dutch and the translations from your code. Can it harm anything to have it this way? Or do you have a different solution?

          Reply
          • Hi Victor, I tested it, and you are absolutely right. The default case in the switch statement does cause text to revert to en_US, even when the WordPress language is set to nl_NL. Removing the default case resolves this issue. I will add a notice to the tutorial to inform others of this behavior.

  • Exceptional post however I was wondering if you could write a litte more
    on this subject? I’d be very thankful if you could elaborate a little bit more.
    Thank you!

    Reply
  • You need to take part in a contest for one of the most
    useful sites online. I most certainly will highly recommend this site!

    Reply
  • I’m really loving the theme/design of your web site.
    Do you ever run into any web browser compatibility problems?

    A small number of my blog readers have complained about my site not operating correctly in Explorer but looks great in Opera.

    Do you have any advice to help fix this problem?

    Reply
  • This site waѕ… how do you say it? Reⅼevаnt!! Finally I havе found something
    that helped mе. Appreciate іt!

    Reply
  • Hi, the second code doesn’t work here, it gives this error on 2nd line

    syntax error, unexpected ‘$text’ (T_VARIABLE)

    Reply
    • Hi Daniel, please share your full function for me to review. Also note that you can only translate text which is wrapped in a translation function __() or _e().

      Reply
  • Heya i’m for the first time here. I found this board and I
    find It truly useful & it helped me out much. I hope to give something
    back and help others like you helped me.

    Reply
  • Hi! Thank you for sharing this content. Could you do one that hides the text instead of translating it? Thanks.

    Reply
  • Hi! Thanks for the informative article and the code 🙂 I tried to use the code to translate 2 different words, so I put the first word in the code (with the translation), and it worked great! But then I added the second word in a similar code and put that into my functions file as well, but that didn’t work. It seems that I can only use the code one time. What should I do to translate more than one word/phrase?

    Reply
    • Hi Eirik,

      For mulitple words you should use the $text array. That’s the second codepart. That should work!

      Reply
  • I am actually thankful to the holder of this web page who
    has shared this great piece of writing at at this time.

    Reply
  • Wohh just what I was searching for, regards for putting up.

    Reply
  • Oh my goodness! Impressive article dude! Thanks, However I am experiencing troubles with your RSS.
    I don’t know why I can’t join it. Is there anyone else having the same RSS issues?
    Anyone that knows the answer can you kindly respond? Thanx!!

    Reply
  • I am actually grateful to the owner of this site who has shared this
    fantastic post at at this time.

    Reply
  • Sory, but it doesnt work for me also.
    My code:
    function change_translate_text( $translated_text ) {
    if ( ‘CONTINUE READING’ === $translated_text ) {
    $translated_text = ‘Kontynuuj czytanie’;
    }
    return $translated_text;
    }
    add_filter( ‘gettext’, ‘change_translate_text’, 20 );

    https://ludzkieseo.pl/blog/

    Reply
    • Hi Jacek,

      Thanks for your feedback! Please note that this only works if text is wrapped with __(); or _e(); function. Can you check if this is the case?

      Please also note that gettext() is case sensitive. If I inspect your button I see it’s written as: Continue reading and styled with CSS to make it uppercase.

      Reply
  • Very nice script, thank you,
    is there a way to use a condition, like when the user change the language on the site then the script runs
    example, it says Old Text 1 and when switching language it becomes New Text 1

    Reply
    • Hi So,

      That’s a very good question! I havent tried that one before. I assume your using WPML to change language?

      Maybe something like this would work:


      function change_translate_text( $translated_text ) {
      if ( 'Old Text' === $translated_text ) {
      if ( ICL_LANGUAGE_CODE === 'fr' ) {
      $translated_text = 'FR Text!';
      } elseif ( ICL_LANGUAGE_CODE === 'nl' ) {
      $translated_text = 'NL Text!';
      }
      }
      return $translated_text;
      }
      add_filter( 'gettext', 'change_translate_text', 20 );

      Reply
  • You genius!

    I’ve been wasting hours using Loco plugin but your first function fixed it for me straight away.

    Reply
    • Hi Tony!
      What approach isn’t working? Let me know so I can check with you.

      Reply

Your thoughts matter, leave a reply 💬

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