问题
After upgrading to WordPress 4.7, I changed the language field from my profile to english, while the site's language is set to greek.
I have written a plugin that displays a widget. This widget is refreshing its content via an ajax call. As it is mentioned here (see Note about admin-ajax.php), strings are normally returned in my profile's language (english), but I would prefer to have them in the site's locale (greek).
After adding the statement switch_to_locale( get_locale() )
at the first line of the ajax call action handler, expressions using the default text domain like __( 'Sunday' )
are indeed translated to greek. However, expressions like __( 'Sunday', 'my-plugin-textdomain' )
are never translated.
My question is how can I display strings from the plugin text domain in my site's (and not my profile's) locale during an ajax call?
Note that:
- Before switching my profile's locale to english, everything worked fine (that is, all strings were translated to greek).
- I am loading the plugin's textdomain in a function triggered by the action plugins_loaded.
- Searching the internet didn't lead to helpful results as the feature of setting the user's locale is released recently in the latest version.
回答1:
It's a late answer but I found out how to load the related text domain before the AJAX call works today, needed to share here:
Add a hidden input field to your form or append to your data this:
<input type='hidden' name='lang' value='<?php echo get_locale();?>'>
or
{
lang: '<?php echo get_locale()?>',
}
Then, just before your load_*_textdomain()
function call, write this:
if (isset($_GET["lang"])) {
$locale = $_GET["lang"];
add_filter('determine_locale', function()use($locale){ return $locale; });
}
It'll switch the locale to the desired locale. Note, the locales are like en_US
or el
relative to your .mo
filenames.
来源:https://stackoverflow.com/questions/41731657/in-a-wordpress-plugin-admin-ajax-call-which-is-the-way-of-using-the-sites-loca