I have been recently working on a website which is required to be available in multiple languages, this is something that Joomla makes fairly simple. Through its implementation of language files and language packs, it is easy to have multiple versions of your site. But can it be done on a click of a button?

We write our sites with a lot of custom components and as such this hindered my progress. I could not simply use a 3rd party add on such as JoomFish due to the fact that on this project we are using our own custom article manager and display component. So I have been racking my brain on how to change Joomla’s language at run time (when the page loads, or on a button click etc). The usual google search and trawl of the Joomla forums did not prove too helpful until one thread pointed me in the right direction, thanks a lot hjortsberg!

Essentially the key to changing the language is getting the JLanguage object from Joomla core and setting it’s language and scope correctly. You do this by passing it a 5 character language code (e.g. en-GB) and the name of a component or module.

/* Set your tag */
$tag = 'es-ES';

/* Set your extension (component or module) */
$extension = 'com_yourcomponent';

/* Get the Joomla core language object */
$language =& JFactory::getLanguage();

/* Set the base directory for the language */
$base_dir = JPATH_SITE;

/* Load the language */
$language->load($extension, $base_dir, $tag, true);

You could set the tag from a cookie, or pass it from elsewhere, this is just a hardcoded example. This code can be run from the constructor of a component or from a module. It will then change the site language and enable JTEXT::(“) messages to be interpreted properly, in that they will use any available language files.

Happy coding :)