Adding support for localization to a WordPress plugin

WordPress uses GNU gettext, as explained in Translating WordPress and Writing a Plugin, for localization. I decided that my plugins should support l10n too. Here is how i realised it:

I started with defining the WPLANG constant in my wp-config.php:

define ('WPLANG', 'en_EN');

Then i changed the beginning of my localized plugin as following:

<?php
/*
Plugin Name: WP-SpamFilter
Version: 0.4
Plugin URI: http://timvw.madoka.be/?p=533
Description: Mark the new comment as spam if the sender is in the spammers list.
Author: Tim Van Wassenhove <timvw@users.sourceforge.net>
Author URI: http://timvw.be
*/

// If this function does not exist it means that the file is accessed directly.
// Accessing this file directly is not allowed.
if (!function_exists('load_plugin_textdomain')) {
  exit;
}

load_plugin_textdomain('wp_spamfilter', 'wp-content/plugins/wp-spamfilter');

In wp-includes/wp-l10n.php you see that the result of this call is that the locale and the path are used to determine the mo-file to be loaded. Because this function uses ABSPATH it’s impossible to use dirname(__FILE__) as path parameter :(

The _e($string, $domain) function echos a localized string and the __($string, $domain) function returns a localized string that you can use in function calls etc… Below you can see an example of the original version and the updated version with localization support:

<h2>some string</h2>
<?php echo('some other string'); ?>
<h2><?php _e('some string', 'wp_spamfilter'); ?></h2>
<?php echo(__('some other string', 'wp_spamfilter')); ?>

Then i used xgettext to extract all the strings that should be localized into wp_spamfilter-en_EN.po:

xgettext –keyword=__ –keyword=_e –default-domain=wordpress –language=php *.php –output=wp_spamfilter-en_EN.po

After that i editted the po file and i compiled a mo file with it using msgfmt:

msgfmt wp_spamfilter-en_EN.po -o wp_spamfilter-en_EN.mo

Once i had made sure that wp_spamfilter-en_EN.mo was readable by my webserver i was ready.

This entry was posted on Sunday, March 19th, 2006 at 02:34 and is filed under WordPress. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.