【问题标题】:wordpress plugin translation does not workwordpress 插件翻译不起作用
【发布时间】:2021-09-18 07:50:45
【问题描述】:

我创建了一个插件“translation_test”来测试 wordpress 的翻译能力。

翻译文件

在语言目录中有一个文件 translation_test.pot 包含:

msgid "Testing"
msgstr ""

还有一个文件 translation_test-de_DE.po:

msgid "Testing"
msgstr "Das ist ein test"

使用 gettext 我已经用这个命令创建了相应的 .mo 文件:

msgfmt translation_test-de_DE.po -o translation_test-de_DE.mo

我已将所有 3 个文件上传到插件的语言目录:./translation_test/languages/

插件php文件:

还有一个名为“translation_test”的 php 文件,其中加载了文本域,并创建了一个管理页面来显示翻译后的文本:

<?php

/*
Plugin Name: translation_test
Plugin URI: 
Description: translation_test
Version: 1.0
Author: 
Author URI: 
Text Domain: translation_test
*/

function translation_test_init_textdomain()
{
    load_plugin_textdomain( 'translation_test', false, dirname( plugin_basename( '__FILE__' ) ) . '/languages/' );
}
add_action( 'init', 'translation_test_init_textdomain' );

/**
 * Register a custom menu page.
 */
function wpdocs_register_my_custom_menu_page(){
    add_menu_page( 'title','custom menu','manage_options','custompage','my_custom_menu_page','',6 ); 
}
add_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' );
 
function my_custom_menu_page()
{
    echo __( 'Testing', 'translation_test' );
}

?>

语言设置

在 wordpress 的管理区域中,我将语言设置为德语,另外我在 wp-config.php 文件中添加了以下行:

define ('WPLANG', 'de_DE');

很遗憾,翻译不起作用,它总是显示“正在测试”。有谁知道错误在哪里?是否有一些简单的插件模板具有我可以使用的工作翻译?

【问题讨论】:

    标签: wordpress wordpress-plugin-creation po mo


    【解决方案1】:

    试试这个:

    //get User Locale
    $user_locale = get_user_locale();
    
    // load text domain and .mo file
    load_textdomain('your_text_domain', $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/your_plugin/your_text_domain-'.$user_locale.'.mo');
    
    // function to use with locale hook
    function wpsx_redefine_locale($locale){
      global $user_locale;
      if ($user_locale == ''){
        return "en_US";
      } else {
        return $user_locale;
      }
    }
    
    // define locale hook
    add_filter('locale','wpsx_redefine_locale',10);
    // test translation
    echo __('test','your_text_domain');
    

    观察: 我使用 LOCO translate 来管理我的文本域以及 .mo 和 .po 文件。 https://br.wordpress.org/plugins/loco-translate/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-11
      • 2020-04-03
      • 1970-01-01
      • 2016-01-10
      • 2013-05-10
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      相关资源
      最近更新 更多