問題描述
我知道我可以讓我的翻譯成 JavaScript:
$MyTranslations = array(
'translation1' => __("Some String 1", "MyTranslations"),
'translation2' => __("Some String 2", "MyTranslations")
);
wp_localize_script( 'jquery', 'my_translations', $MyTranslations );
但是看一些 WordPress TinyMCE 外掛,他們使用這樣的電話:
{
title : ed.getLang('advlink.link_desc'),
...
}
WordPress 如何將其翻譯成 getLang()
?我應該這樣做,或者我只是使用我的第一個程式碼,並直接訪問變數:
{
title : my_translations.translation1,
...
}
最佳解決方案
使用過濾器'mce_external_languages'
。來自 wp-includes/class-wp-editor.php
:
The following filter loads external language files for TinyMCE plugins. It takes an associative array ‘plugin_name’ => ‘path’, where path is the include path to the file. The language file should follow the same format as
/tinymce/langs/wp-langs.php
and should define a variable $strings that holds all translated strings. When this filter is not used, the function will try to load{mce_locale}.js
. If that is not found, en.js will be tried next.
$mce_external_languages = apply_filters('mce_external_languages', array());
我只是使用 wp-includes/js/tinymce/langs/wp-langs.php
… 的副本,並放棄多餘的 mce_escape()
贊成原來的 esc_js()
。
示例檔案:
<?php # -*- coding: utf-8 -*-
$strings = 'tinyMCE.addI18n(
{' . _WP_Editors::$mce_locale . '.extrastrings:
{
helloworld: "' . esc_js( __( 'Hello World', 'my_plugin_text_domain' ) ) . '",
foobar: "' . esc_js( __( 'Foo Bar', 'my_plugin_text_domain' ) ) . '"
}
}
)';
在您的外掛中,您只需使用:
add_filter( 'mce_external_languages', 'wpse_44785_add_tinymce_lang', 10, 1 );
function wpse_44785_add_tinymce_lang( $arr )
{
$arr[] = 'full_path_to_lang_file.php';
return $arr;
}
要使用 JavaScript 來訪問新的字串,例如:
title : ed.getLang('extrastrings.helloworld')
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。