【问题标题】:Get localized string for specific locale获取特定语言环境的本地化字符串
【发布时间】:2013-09-21 00:38:43
【问题描述】:

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

背景:我有一个自定义主题,我使用区域设置“en_US”作为默认区域设置,并通过 PO 文件转换为区域设置“es_ES”(西班牙语)。

假设我使用了结构

__('Introduction', 'my_domain');

在我的代码中,并且我已在我的 PO 文件中将“Introduction”翻译成西班牙语“Introducción”。这一切都很好。

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

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

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

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

__('Introduction', 'my_domain');

根据当前语言环境获取“介绍”或“介绍”。

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

SITE_ID  CAT    TEXT             LOCALE
123      intro  Introduction     en_US
123      intro  Introducción     es_ES

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


通过包含插件 PolyLang 扩展问题:是否可以使用 Custom Strings 来实现上述功能?例如。概念上:

pll_('Introduction', $locale)

【问题讨论】:

    标签: wordpress localization


    【解决方案1】:

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

    从一个简单的示例开始,您可以确切地知道要加载哪些语言环境以及 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');
    }
    

    这假设您的 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 );
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-25
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多