WP Development

Writing a custom plugin that can be translated by WPML (WordPress Multilingual) using .mo files is actually quite simple once you figure out how to generate the .mo file. My first attempt to internationalize my plugin with WPML however was less than successful, WPML would not localize my plugins text strings. I knew my .mo file was correct, and could be loaded by WordPress because when I set WPLANG to my target locale in wp-config.php, my plugins text was correctly translated. Selecting a language using WPML however, had no effect.

A little bit of digging through the WPML source eventually uncovered my mistake: I was simply calling load_plugin_textdomain() too early! I was loading my plugins text domain in my plugins constructor, which of course happened after the WPLANG constant was defined, but before WPML had a chance to set the selected locale, which explained why my translation worked for the one but not the other. Moving the call to load_plugin_textdomain() to the init action gave WPML time to set the locale first:

add_action( 'init', 'plugin_init' );

function plugin_init() {

  // localization in the init action for WPML support
  load_plugin_textdomain( 'my_textdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );

}

And now my plugins can be internationalized by WPML. Woo!

Published by Justin Stern

Justin is one of our co-founders, and is our resident overengineer. He likes to write developer tutorials and make black magic happen in our plugins. He thinks that writing code is a lot easier than writing words.