在WordPress插件admin ajax调用中,使用网站区域设置的方法是什么? [英] In a WordPress plugin admin ajax call, which is the way of using the site's locale?

查看:75
本文介绍了在WordPress插件admin ajax调用中,使用网站区域设置的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升级到WordPress 4.7后,我将语言字段从我的个人资料更改为英语,而网站的语言设置为希腊语.

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.

我写了一个显示小部件的插件.该小部件正在通过ajax调用刷新其内容.正如提到的那样

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).

在ajax调用操作处理程序的第一行添加语句switch_to_locale( get_locale() )之后,使用默认文本域(例如__( 'Sunday' ))的表达式确实会转换为希腊语.但是,像__( 'Sunday', 'my-plugin-textdomain' )这样的表达式永远不会被翻译.

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.

我的问题是在进行Ajax调用时,如何在我的网站(而不是我的个人资料)的语言环境中显示来自插件文本域的字符串?

请注意:

  • 在将我的个人资料的语言环境切换为英语之前,一切正常(也就是说,所有字符串都被翻译成了希腊语).
  • 我正在通过操作 plugins_loaded 触发的函数中加载插件的textdomain.
  • 搜索互联网并没有带来有用的结果,因为设置用户区域设置的功能最近发布了最新版本.
  • 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.

推荐答案

这是一个很晚的答案,但我发现如何在今天的AJAX调用生效之前加载相关的文本域,需要在此处共享:

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();?>'>

{
   lang: '<?php echo get_locale()?>',
}

然后在load_*_textdomain()函数调用之前,编写以下代码:

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; });
}

它将语言环境切换到所需的语言环境.请注意,相对于.mo文件名,语言环境类似于en_USel.

It'll switch the locale to the desired locale. Note, the locales are like en_US or el relative to your .mo filenames.

这篇关于在WordPress插件admin ajax调用中,使用网站区域设置的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆