Translate Template Strings with Polylang String Translation

Polylang is one of the multilingual plugins I often recommend for WordPress. One especially useful feature is its string translation system, which makes it easy to translate fixed strings that appear inside theme templates.

When developing a single-language theme, hardcoding interface strings is often fine. In a multilingual site, though, those strings also need to be translated. One option is the traditional Gettext workflow. Another is Polylang’s string translation feature.

Register the strings that need translation

Before Polylang can translate a string, the string needs to be registered. That is as simple as calling pll_register_string(). Once registered, the strings appear in the admin area under Languages → String translations.

$strings = array(
    'Hot Videos',
    'Read More',
    'Read All',
);

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

Output the translated string in your template

Where you would normally output a fixed string, replace it with pll__() so the correct translation is returned for the current language.

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

One important detail is that the string used on the front end must match the registered string exactly. Differences in spacing, punctuation, or capitalization will prevent Polylang from finding the translation.

Compared with a full Gettext workflow, Polylang string translation is simpler and friendlier for site administrators who are not comfortable editing language files. The tradeoff is that Gettext can be more efficient, but on small or cached sites the difference is often negligible.

Related Posts

Leave a Reply

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