Question

I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate.

So I ended up with this function:

function __2($string, $textdomain, $locale){
  global $l10n;
  if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain];
  load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo');
  $translation = __($string,$textdomain);
  if(isset($bkup)) $l10n[$textdomain] = $backup;
  return $translation;
}

Now, as per this famous article, I really shouldn't have coded that function :

http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/

...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works?

Was it helpful?

Solution 2

The answer is: sometimes. As long as you know what you are doing, there are no problems in terms of bugs. There can be situations where this is possible and safe, and other where it can be necessary or extremely useful.

To complete and share the code above, I add the following:

function _e2($string, $textdomain, $locale){
  echo __2($string, $textdomain, $locale);
}

// example

_e2('hello','stratboy','it_IT');

UPDATE:

Some bonus code can be found here:

How to get a traslated string from a language other than the current one?

OTHER TIPS

No it does not work, people that will need to translate the string will not be able to use the automated tools they usually use to extract the strings that need translation.

And yes, it is always bad.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top