Preparing Strings for Localization in Themes and Plugins

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:

echo ‘<h3>Thumbnail and Excerpt Settings</h3>’;

If someone wants to translate the plugin to another language, they are stuck with that string, not good!

So lets add localization:

echo ‘<h3>’ . __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ ) . ‘</h3>’;

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.

$str = __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ );
echo “<h3>$str</h3>”;

And another way using the printf() function:

printf( ‘<h3>%1$s</h3>’, __( ‘Thumbnail and Excerpt Settings’ , ‘wprss’ ) );

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.

Add a Comment

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