2017-04-07 95 views
0

使用WPML,我用4種語言翻譯了一個字符串:en,nl,fr和de。WPML獲取所有語言字符串的翻譯內容(如果有的話)

默認情況下,我可以使用<?php _e('my string here','text_domain'); ?>,當我在該域中時,它將返回確切的翻譯文本。

我怎樣才能在一個地方獲得所有的翻譯文本。所以,如果我在網站的英文版本上,但我想要獲取我的字符串在nl,fr,de和en的翻譯內容。

我可以知道這怎麼可能?

回答

1

您可以臨時更改當前語言以檢索翻譯後的字符串。喜歡的東西:

// Backup the current language 
$current_lang = $sitepress->get_current_language(); // Say it's "en" 

// Switch to another language. E.g. $desired_lang = "nl"; 
$sitepress->switch_lang($desired_lang); 

// Get your translated string... 
_e('My string here', 'text_domain'); 

// Back to the original language to not interfere 
$sitepress->switch_lang($current_lang); 

我已經在頁面模板測試這個(比如index.php)和它的作品...然後我試圖建立一個函數來完成這項工作。喜歡的東西:

// Put this in your functions.php 
function get_all_translations($string, $languages) { 

    global $sitepress; 

    if (empty($languages)) { 
     $languages = array_keys(
      icl_get_languages('skip_missing=0&orderby=code&order=asc') 
     ); 
    } 

    $current_lang = $sitepress->get_current_language(); 

    $translations = []; 
    foreach ($languages as $lang) { 
     $sitepress->switch_lang($lang, true); 
     $translations[$lang] = __($string, 'text_domain'); 
    } 

    $sitepress->switch_lang($current_lang); 
    return $translations; 
} 

和:

// This on index.php: 
var_dump(get_all_translations('My string here')); 
var_dump(get_all_translations('My string here', ['nl', 'fr'])); 

但它不工作,我想不通的原因......我希望這有助於反正。

+0

謝謝。這有幫助。我只用3種語言切換語言,將字符串存儲在變量中並使用它們。 –