获取特定区域设置的本地化字符串

fri*_*gel 5 wordpress localization

如何使用 WordPress 中的本地化机制来访问现有但不是当前的语言字符串?

\n\n

背景:我有一个自定义主题,我使用语言环境 \'en_US\' 作为默认语言环境,并通过 PO 文件转换为语言环境 \'es_ES\' (西班牙语)。

\n\n

假设我使用该结构

\n\n
__(\'Introduction\', \'my_domain\');\n
Run Code Online (Sandbox Code Playgroud)\n\n

在我的代码中,并且我已将 PO 文件中的“Introduction”翻译为西班牙语“Introducci\xc3\xb3n\xc2\xb4”。这一切都运行良好。

\n\n

现在问题是:我想在数据库中插入 n 条记录,其中包含字符串“Introduction”的所有现有翻译 - 每种语言一个;因此,在我的示例中,n = 2。

\n\n

理想情况下,我会写这样的东西:

\n\n
$site_id = 123;\n// Get an array of all defined locales: [\'en_US\', \'es_ES\']\n$locales = util::get_all_locales();\n// Add one new record in table details for each locale with the translated target string\nforeach ($locales as $locale) {\n    db::insert_details($site_id, \'intro\',\n        __(\'Introduction\', \'my_domain\', $locale), $locale);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

只是,上面 __() 中的第三个参数对我来说纯粹是幻想。你只能有效地写

\n\n

__(\'简介\', \'my_domain\');

\n\n

根据当前区域设置获取“Introduction”或“Introducci\xc3\xb3n\”。

\n\n

理想情况下,上面代码的结果是我的表中最终有两条记录:

\n\n
SITE_ID  CAT    TEXT             LOCALE\n123      intro  Introduction     en_US\n123      intro  Introducci\xc3\xb3n     es_ES\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

我知道我想要一些需要加载所有 MO 文件的东西,通常情况下,只需要当前语言的 MO 文件。也许使用 WordPress 函数 load_textdomain 是必要的 - 我只是希望已经存在一个解决方案。

\n\n
\n\n

通过包含插件 PolyLang 来扩展问题:是否可以使用自定义字符串来实现上述功能?例如,从概念上讲:

\n\n
pll_(\'Introduction\', $locale)\n
Run Code Online (Sandbox Code Playgroud)\n

Tim*_*Tim 3

我知道这个老问题,但这里是 -

从一个简单的示例开始,您确切知道要加载的区域设置以及 MO 文件的确切位置,您可以直接使用 MO 加载器:

<?php
$locales = array( 'en_US', 'es_ES' );
foreach( $locales as $tmp_locale ){
    $mo = new MO;
    $mofile = get_template_directory().'/languages/'.$tmp_locale.'.mo';
    $mo->import_from_file( $mofile );
    // get what you need directly
    $translation = $mo->translate('Introduction');
}
Run Code Online (Sandbox Code Playgroud)

这假设您的 MO 文件都在该主题下。如果您想在 WordPress 环境中添加更多这种逻辑,也可以,但这有点令人讨厌。例子:

<?php
global $locale;
// pull list of installed language codes
$locales = get_available_languages();
$locales[] = 'en_US';
// we need to know the Text Domain and path of what we're translating
$domain = 'my_domain';
$mopath = get_template_directory() . '/languages';
// iterate over locales, finally restoring the original en_US
foreach( $locales as $switch_locale ){
    // hack the global locale variable (better to use a filter though)
    $locale = $switch_locale;
    // critical to unload domain before loading another
    unload_textdomain( $domain );
    // call the domain loader - here using the specific theme utility
    load_theme_textdomain( $domain, $mopath );
    // Use translation functions as normal
    $translation = __('Introduction', $domain );
}
Run Code Online (Sandbox Code Playgroud)

这种方法比较糟糕,因为它会破坏全局变量,并且需要随后恢复原始语言环境,但它的优点是使用 WordPress 的内部逻辑来加载主题的翻译。如果它们位于不同的位置,或者它们的位置受到过滤器的影响,这将很有用。

我还在本示例中使用了get_available_languages,但请注意,您需要为此安装核心语言包。除非您还安装了核心西班牙语文件,否则它不会在您的主题中选择西班牙语。