Wordpress Plugin Tutorial Part XI - Localizing the Plugin

Now that we have the functionality that we want we will add the finishing touches to the plugin.
Firstly we will take a look at how to localize the plugin.

If you remember the  part two of the tutorial series, we created a folder called custom-comment-message in order to keep our plugin files. Within this folder we will create another folder called 'languages' to keep teh files related to different languages. Next we will have tell Wordpress where these files are kept. To do this we use the following function which is within the 'CustomCommentMessage' class.
function load_ccm_textdomain(){

This page contains more information about the 'load_plugin_textdomain' function. To explain briefly, the first parameter is a unique parameter to our plugin and will be used to identify what files to use to translate a certain string. The third parameter specifies where to find the files.
Next we will hook the above function to the 'init' action. To do so put the following code in the constructor function.

add_action( 'init', array(&$this,'load_ccm_textdomain') );

Now we must make all strings that we show in the user interface translatable. There are two methods that we use to do this. As an example we will take the  'add_ccm_meta_box' function. The following shows the changed code.
public function add_ccm_meta_box()
        ,__('Custom Comment Message','ccm_textdomain')
        ,array( &$this, 'render_ccm_meta_box_content' )
Previously the second parameter was 'Custom Comment Message'. Now we have changed it to __('Custom Comment Message','ccm_textdomain'). By doing so we specify that the string 'Custom Comment Message' has to translated using the 'ccm_textdomain'. The '__' is the function that we have used to do so.

There is another function that we use to provide localization ability. That is '_e' function. The following code shows how this can be used.
function ccm_section_text() {
     '<p>'._e('Set the default comment message 
        that you would like to use.','ccm_textdomain').'</p>';
It is almost the same as the '__' function except it echoes the content. We have to do the same for all other strings shown on the user interface.

To translate the plugin to another language, we have to generate a '.mo' file using a software like Poedit there is also a Wordpress plugin that allows the easy translation of  plugin called Codestyling Localization. There are tutorials on using Poedit and Codestyling Localization. Remember to put the generated '.mo' file in the 'languages' directory within the plugin directory. Also the '.mo' file should be named in the form {text-domain}-{locale}.mo.

No comments:

Post a Comment