Gettext on WordPress from zero

WordPress use the functions __ and _e for translating.

This quick tutorial explains how to create a new POT file for pt_BR.

cd /WORDPRESS_DIR/wp-content/themes/THE_THEME/
mkdir languages
touch languages/pt_BR.po
find . -iname "*.php" | xargs xgettext -j -o languages/pt_BR.po -k__ -k_e

Where

  • -j OR --join-existing => Join messages with existing file.
  • -k[keywordspec] OR --keyword[=keywordspec] => Specify keywordspec as an additional keyword to be looked for.
  • -o file --output=file => Write output to specified file (instead of name.po or messages.po).

Change following lines accordingly:

"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2013-03-25 22:37-0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Rafael Goulart <rafaelgou@gmail.com>\n"
"Language-Team: RGOU <rafaelgou@rgou.net>\n"
"Language: Brazilian Porguese \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

Don’t forget to change the charset to UTF-8.

Now transalate the POT file you’ve created, and finally make the MO file:

msgfmt languages/pt_BR.po -o languages/pt_BR.mo

You can add more translations just running xgettext command again to add new entries,
translating and regenerating the MO file:

find . -iname "*.php" | xargs xgettext -j -o languages/pt_BR.po -k__ -k_e

… do your new translations and:

msgfmt languages/pt_BR.po -o languages/pt_BR.mo
  • Thank you for your informative article. Very difficult to find information specific on xgettext and its usage with WordPress custom gettext functions. With the addition of plural and context aware gettext functions like _x and _nx, esc_attr_e and a dozen others, the xgettext commands -k keyspec argument in your examples should be expanded to include all the various function calls which have strings to extract to the .po file which may appear in a users custom theme or plugin. To make this process simpler, a developer should check out the wordpress-i18n tools from wordpress svn repositority as it includes a script “makepot.php” which can be run which extract all the strings from the many WordPress custom gettext functions:

    http://i18n.svn.wordpress.org/tools/trunk/

    run makepot for a plugin like this:

    php makepot.php wp-plugin your-plugin-directory

    run makepot for a theme like this:

    php makepot.php wp-theme your-theme-directory