WordPress Plugin Localization with NPM and Grunt

On November 13, 2016, in Other Online Technology, by James Liu

Localization is very important if you want your applications to be used world wide. These days I was trying to create a WordPress plugin and my last job is localizing it in Chinese version. WordPress uses the gettext libraries and tools for i18n (internationalization). Though PHP provides a great built-in functions for localization, WordPress defines its own function __() to handle the job. In WordPress developer website, they only provide the direction but not the details about how to localize the plugin. I spend two days to successfully localize my WordPress. I find the materials is not enough on WordPress website and it’s better to gather all information in one page. Therefore, I decide to write this WordPress plugin localization guide. This tutorial will demonstrate how to localize a WordPress Plugin step by step.

Quote All Text with __()

When we are creating the WordPress plugin at the beginning, we need to remain all text localizable. For example, I want to show a title text “My Title”. The title will be localized. So I need to write the PHP code like this:

<?php //>
echo "<title>".__("My Title", "my-plugin")."</title>";
?> 

“My Title” is the text I want to be localized. “my-plugin” is the text domain according to WordPress document. Here I don’t think it is necessary to understand what’s text domain, just keep in mind, the text domain is the same as your plugin name with dash. For example, my plugin name is “My Plugin”, and my plugin folder is “my-plugin”, so the text domain will be “my-plugin”.

This step is very important and you will know the reason why it is so important in next step.

Prepare POT File with NPM, Grunt and Grunt-POT Plugin

POT file is short name of “Portable Object Template). This file will contain the original strings (in English) in the plugin. For above example, the file will contain following content:

msgid "My Title"
msgstr ""

msgid will be the content we want to localized and the msgstr will be the localized content.

We don’t have to create POT file by ourselves manually. We can use NPM and Grunt to create this template with other several tools. This part is not included in WordPress document, and it takes me a long time to figure it out how to make it working. Here is a list of tools we need to install before we can create POT file automatically.

  • Node.js
  • NPM
  • Grunt: NPM plugin
  • Grunt-POT: Grunt plugin
  • Eazy Po: A gettext tool set includes xgettext and msgfmt. This tool set will be used by Grunt-POT

Here I will brief the steps to setup this environment for creating POT file.

  • Download the install Node.js here.
  • Run the following commands in plugin folder
  • cd my-plugin
    npm init
    npm install -g grunt-cli
    npm install --save-dev grunt
    npm install --save-dev grunt-pot
    
  • Prepare Grunt configuration file
  • The grunt configuration file is a js file “Gruntfile.js”. It is located in the plugin root folder, where NPM configuration file “package.json” is located in. Here is my example grunt configuration file:

    module.exports = function(grunt) {
        grunt.initConfig({
            pkg: grunt.file.readJSON('package.json'),
            pot: {
                options: {
                    text_domain: 'my-plugin',
                    dest: 'languages/',
                    keywords: ['gettext', '__']
                },
                files: {
                    src: ['**/*.php', '!node_modules/**'],
                    expand: true
                }
            }
        });
    
        grunt.loadNpmTasks('grunt-pot');
    
        grunt.registerTask('default', ['pot']);
    };
    
  • Run following command to generate POT file
  • grunt
    

After you run above command, you may meet following error message:

Warning: Command failed: xgettext

This is because you don’t install the xgettext (xgettext.exe in windows) or grunt cannot find xgettext on your path. If you are working on Windows, then you can download this free app Eazy Po. The “xgettext” is located in gettext folder. You can put this folder in your system Path. Then you can run grunt command again and the warning message will go.

After you run grunt command successfully, you will get a POT file “my-plugin.pot” in languages folder. Now, you can go to next step to localize your plugin with different languages.

3. Create PO and MO Localized File
In this step, I will show you how to localize the plugin file from POT file. In my example, I will translate my plugin in Simple Chinese. So I will copy my-plugin.pot as my-plugin-zh_CN.po. If you want to translate in Australia English, the PO file will be my-plugin-en_AU.po. Then I will put the localized content in this PO file. This is my example localized PO file in Chinese:

msgid "My Title"
msgstr "????"

After finishing all translating job, we can run following code to generate MO file. Later, WordPress will load MO file to find the translated text.

cd languages
msgfmt -o my-plugin-zh_CN.mo my-plugin-zh_CN.po

In this step, we may get following error message:

Warning: Charset “CHARSET” is not a portable encoding name. Message conversion to user’s charset might not work.

Don’t worry about it. Please find follow line in your PO file:

"Content-Type: text/plain; charset=CHARSET\n"

Change to:

"Content-Type: text/plain; charset=UTF-8\n"

Load localization file in WordPress Plugin and Test

After we successfully create MO file, please don’t forget to add following action in your plugin file. It will tell WordPress where to load the localization file for your plugin.

add_action( 'init', 'myplugin_load_textdomain' );

function myplugin_load_textdomain() {
  load_plugin_textdomain( 'my-plugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); 
}

After this step, we finish the localization task. I hope this localization tutorial will be helpful. If you have any comment, you can leave the comment below.

 

Leave a Reply

WordPress Themes

Free WordPress Themes