I wonder, is there a way to change the locale at runtime using WordPress ?
What I mean, is, I have create a custom URL in order to create an XML file with data for integration with another web application. The URL has also a language portion. Lets say this is my URL
http://example.com/custom/url/en
where last portion of the URL is the english language. In that case what I like is the WordPress to generate an English XML. But how can I instruct the WordPress to change the locale in that point of the execution ?
Note that I have to change the locale because I use also system variables that are translated, such us __(), _e() and so on.
I’m trying to do a similiar thing, and the experts on the wp-hackers mailing list (Otto, Nacin) told me this:
So the best solution is to apply a filter on the ‘locale’ global variable. The only way to do that is by creating a custom plugin. If you put the following piece of code into your
functions.php
file, it won’t work properly because it will run too late in the WP loading sequence.Your plugin could look like this (I’m just reusing the URI testing part from OneTrickPony, you can replace it with another conditional testing method):
I hope this can help anyone!
A few more warnings (quoting Andrew Nacin), regarding the cost in terms of performance when switching the locale:
See http://codex.wordpress.org/Plugin_API/Action_Reference for useful info about the loading sequence.
I don’t know if it’s possible to do this within a plugin, because of the constants WP requires defined before a certain point, but check for the requested language in wp-config.php and define the necessary constant:
At first, ensure that your desired locale is in a list (under “has a language pack“). If confirmed, then use such code:
If you haven’t chosen that language in WP dashboard, then you might need to use installer hook programatically: