dounuogong0358 2014-01-21 14:59
浏览 63

Wordpress不会通过ajax请求加载正确的语言mo文件

I made a wordpress theme and set it up in two languages (EN and DE). I also made the required mo-files. I defined german as default language in wp-config.php in the beginning. Everything works fine but I have some problems with AJAX requests: It doesn't load the correct language files.

My scenario:

I made a Button/Link requesting data via AJAX. Something like this (javascript):

jQuery('#button').click(function(){
 jQuery.ajax({
  url: "http://myexampledomain.com/wp-admin/admin-ajax.php?lang=en",
  data: { action: 'my_action', id : 123 },
  type: "POST",
 }).done(function (data){
  alert(data);
 });
});

As you can see, I am trying to load my information in english (url => ?lang=en). I wrote this code in my functions.php:

add_action("wp_ajax_nopriv_my_action", "my_action");
add_action("wp_ajax_my_action", "my_action");
function my_action(){
 echo __( 'ID nicht gefunden:', 'mytheme' ) . $_POST['id'] ;
 exit;
}

My Problem is, that the alert "ID nicht gefunden:123" pops up although it should be "ID not found:123".

It seems wordpress is not loading the correct language mo-file.

To fix this I tried the following in my functions.php (but it didn't work):

add_filter( 'locale', 'my_theme_localized' );
function my_theme_localized( $locale ){
    if ( isset( $_GET['lang'] ) && $_GET['lang']=='en' ){
        return 'en_US';
    }
    return 'de_DE';
}

I also experemented with some plugins: XILI-language, qTranslate and Polylang. The result is that only qTranslate was able to load the correct language file via AJAX request. But qTranslate is not the best solution for some tasks I am working on.

I also found a "workaround" to load the correct mo-file by writing the following into wp-config.php:

if(isset( $_GET['lang'] ) && $_GET['lang']=='en')
 define('WPLANG', 'en_US');
else
 define('WPLANG', 'de_DE');

But I don't like this hack (modifing wordpress core files).

Is there are good solution to make wordpress load the corret mo-file by using $_GET['lang'] parameter in the AJAX request? What piece of code do I need in my functions.php? Any other working solutions?

  • 写回答

1条回答 默认 最新

  • dongsu7049 2019-01-09 09:52
    关注

    I had the same issue, I put the below code to under <?PHP and It fixed my issue

    load_theme_textdomain( LANG, get_template_directory() . '/lang' );

    LANG is your language file name

    评论

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建