How to Translate Template Strings with Polylang String Translation

When developing multilingual WordPress sites, we have recommended two plugins on this site, and Polylang is one of them. The more I use it, the more useful I find it. Today I want to introduce Polylang’s string translation feature.

When developing WordPress themes, we inevitably use some fixed strings in templates. For single-language sites, hard-coding those strings is usually fine. But when developing multilingual sites, that approach no longer works, because those fixed strings also need translation. There are two ways to handle this. One is the Gettext method, and the other is Polylang’s string translation feature.

Register Strings That Need Translation

Before using Polylang string translation, we first need to register the strings that require translation. The registration process is very simple: just use the pll_register_string function and pass two parameters. After registration, these strings will appear in the admin panel under Language -> String translations, where we can edit the translation for each language.

$strings = [
    'Hot Videos',
    'Read More',
    'Read All',
];

foreach ($strings as $s) {
    pll_register_string(sanitize_key($s), $s);
}

Display the String in Templates

Where you originally used a fixed string in the template, replace it with the output of the pll__() function. This allows the translated string to be displayed according to the current language.

 <?= pll__('Read More'); ?>

Note: the string used on the front end must exactly match the registered string, otherwise Polylang cannot output the correct translation. Differences in spaces, punctuation, or letter case will all prevent the translation from being displayed properly.

Compared with the Gettext method, Polylang’s string translation feature is simpler and better suited to site administrators who do not often work with code. First, translations can be managed directly in the WordPress admin without extra software or additional files. Then, when you add new strings, you only need to refresh the admin page. After you add a new language in Polylang, that language will also appear immediately in the string translation interface.

In terms of performance, Polylang is certainly not as efficient as the Gettext method. However, for websites with modest traffic, or sites that already use page caching, the difference between the two methods is not very noticeable.

Related Posts

Leave a Reply

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