Let’s Localize

I spent today figuring out how to internationalize my plugin.

There’s a LOT of different translation functions, and it’s going to take a while to learn when it’s best to use which one, but for now all the text my plugin is adding is translation-ready, so yay!

I mostly followed the steps in Professional WordPress Plugin Development, though it missed a crucial step in how to create the actual .pot file using Poedit: It explained that .po and .mo files must have the locale-id included in the filename, but then proceeded with instructions to create a .pot file which doesn’t contain the locale-id (and which you can’t actually save using Poedit.

After struggling for probably an hour, checking and re-checking my Text Domain and Domain Path, I finally turned to the WordPress StackExchange. It didn’t have my answer exactly, but it pointed me to the plugin handbook on WordPress.org, which explained how to get the .pot file, along with locale-specific .po and .mo files. And my translations worked!

Another challenge was figuring out how to include a link in a string. Just including the URL (including HTML) in the string didn’t work – Poedit for some reason turned quotes into smart quotes in the translation, which broke the link. Next I broke the string up into different parts, which worked, but I realised it will be a problem in languages that change the word order.

I moved the URL (including the opening <a> tag) to a variable, so I could use a placeholder, and just added the closing </a> tag via concatenation…before I realised that’s really dumb – separating the closing tag from the opening one could completely change what’s actually linked should the order of words in the string change.

I was stumped on how to solve it, so took to StackExchange again. I’m a bit confused at this part of the solution: '<a href="%s">%s</a>'. Specifically, why do we repeat the %s placeholder, rather than using numbered placeholders here? I’ll need to ask someone about that.

Some TILs:

  • Text Domain must match the plugin slug/folder name
  • If internationalizing a string you’re echoing, use _e rather than __
  • If using return in a function, printf doesn’t work – use sprintf
  • It’s possible to nest translation functions inside one another

Leave a comment

Design a site like this with WordPress.com
Get started