Preparing WordPress theme (or a plugin) for translation (or internationalization)

In a global world, making sure that WordPress themes or plugins are prepared for easy translation is of the highest importance. By doing that, you’re making sure that your plugin or theme can be translated and used by people who don’t necessarily speak English. And that could sometimes mean millions and millions of users. Therefore, WordPress developers prepared several functions and here are some of them:

__ function

Consider the following example:

In this one, ‘theme-domain’ is your theme text domain and should be the same all across the theme (or plugin). The first string (I am ready to be translated) is what outputs by default (default language).

Note that you can’t add variables where $text variable goes – if you want to do it, you will need placeholders. Here’s an example:

Placeholder is %s and variable is whatever the value get_the_author() returns.

In other words, this will not work:

And the reason is simple – gettext will read text only, and not variables.

_x function

There’s a great example for _x function (and even more for placeholders) in Twenty Fifteen theme – if you check the earlier syntax, the only difference is that it adds context in which translation appears. This is very useful if you have an exact string (such as Posted on) which appears in different templates.

Consider the placeholders first; these are %1$s and %2$s, which means it will accept next two variables (“s” goes for string) in that order. In this case, variables are whatever _x and $tags_list return. In this example, _x returns ‘Tags‘ by default, twentyfifteens is the themes’ textdomain, while ‘Used before tag names’ is description (context) providing information on where this string appears and is very useful for anyone who will translate the theme into their language.

_nx function

Consider the following example:

Whenever you need different wording for cases where you count something (such as 1 comment, 2 comments…) and where you’ll have singular and plural, you will have a great use of _nx function (or _n, given that it is actually _nx, but without the context parameter). In the example above (note that we are also using escapes), _nx will accept two options, depending on number of comments. You can also see that this function accepts variables (comment counter).

There are also some other WordPress functions with similar combinations which you can use depending on what you need. For further reading, I definitely suggest post by Otto in which he covers the topic in more detail.