Many plugin and theme developers fail to properly prepare their plugins and themes for localization.
I suspect that rather than an unwillingness on their part to do this important task, it’s instead a case of getting confused about what’s needed.
So let me give you some examples to show how easy it is to prepare strings for localization.
Let’s say I am building a plugin and I need to output a simple string, to create a settings page header. Without localization it would look something like this:
[php]
echo ‘<h3>Thumbnail and Excerpt Settings</h3>’;
[/php]
If someone wants to translate the plugin to another language, they are stuck with that string, not good!
So lets add localization:
[php]
echo ‘<h3>’ . __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ ) . ‘</h3>’;
[/php]
What have we done here? We’ve used the __() function, which is used to translate a string and returns it as a string. We also add our domain (‘wprss’). This is needed and should be unique for every plugin or theme you develop.
Now the above is not the only way to localize a string, lets see some other examples, and you can decide which one you like best. All of theme work fine.
[php]
$str = __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ );
echo "<h3>$str</h3>";
[/php]
And another way using the printf() function:
[php]
printf( ‘<h3>%1$s</h3>’, __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ ) );
[/php]
In case you’re wondering, printf() is used to output a formatted string. You will probably also encounter sprintf(), a related function which writes a formatted string to a variable instead of outputting it.
For your reference, here are some common localization functions:
__ (double underscore) is the base translate function. It translates a string and returns it as a string.
_e does the same as __, but echo’s the result immediately.
_x is the contextual translate function. It has a second option to provide context to people doing the translation.
_ex is the same as _x, but echo’s the result.
Which style do you like best?
If you enjoyed this post, make sure to subscribe to WP Mayor’s RSS feed.
5 Responses
The markup in your code samples is a mess – perhaps double-encoded? Showing markup samples on a webpage is always a pain!
Thanks for pointing it out, fixed now. It is indeed a pain, I should start using Gists sometime soon to solve this problem.
It would also be great if you would add how to generate a po-File with Poedit.
Hi David, I’ll try to make a screencast at a later stage, time permitting. In the meantime, this is the guide I use:
Jean, this is a very good and simple tutorial to prepare a theme or plugin for localization. But you need to add these functions as well to your plugins or themes/child themes to make it complete:
load_theme_textdomain
load_child_theme_textdomain
load_plugin_textdomain
Please add it to your tutorial to make it more useful to those who just start preparing for localization.