2013-09-16 89 views
3

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

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

让我们说我用的是建设

__('Introduction', 'my_domain'); 

在我的代码,而我在PO文件翻译成“简介”西班牙“Introducción'。所有这些工作正常。

现在的问题是:我想在我的数据库中插入n条记录,其中包含字符串'Introduction'的所有现有翻译 - 每个语言一个;所以,在我的例子中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); 
} 

只是,那上面__()的第三个参数是我的一部分纯粹的幻想。您只能有效编写

__('介绍','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) 

回答

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,但是请注意,您需要为此安装核心语言包。除非您还安装了核心西班牙文件,否则它不会在您的主题中选择西班牙语。

相关问题