Hijacking WordPress Internationalisation

As part of a new feature I am developing for the next release of my Welcome Pack plugin for BuddyPress, I needed a really smart way of dynamically adding my own translations for strings at page-load time; creating a stand-alone .mo file to load the strings wasn’t a great solution, for reasons of requiring people to know how to configure file permissions on the server, having to figure out how to write a .mo file (I wish they were as easy as XML, but they aren’t), and — honestly — doing it that way feels like such a hack.

Here’s how. Be warned that this will overwrite any translation loaded by a .mo file, but that’s exactly what I needed to do.

To add a new string into the localisation table:

function example() {
global $l10n;

$mo = new MO();
$mo->add_entry( array( 'singular' => 'Spongebob', 'translations' => array( 'Squarepants' ) ) );
if ( isset( $l10n['buddypress'] ) )  //buddypress is the textdomain
$mo->merge_with( $l10n['buddypress'] );

$l10n['buddypress'] = &$mo;
}

_e( 'Spongebob', 'buddypress' );  // This will return "Squarepants".

To change an existing string:

function example() {
global $l10n;

if ( isset( $l10n['buddypress'] ) && isset( $l10n['buddypress']->entries['%s posted an update:'] ) )
$l10n['buddypress']->entries['%s posted an update:']->translations[0] = '%s posted a monkey:';
}

Post a comment if you use this technique for anything interesting