說明
將已添加的腳本進行本地化(翻譯)。當然也可用來在一個頁面中包含任意的Javascript數(shù)據(jù)。
用法
<?php wp_localize_script( $handle, $object_name, $l10n ); ?>
參數(shù)
$handle
(字符串)(必填) 你所要附加數(shù)據(jù)的處理腳本
默認值:無
$object_name
(字符串)(必填) 將包含數(shù)據(jù)的腳本對象名稱(也就是所要翻譯文本的前綴)
默認值:無
$l10n
(數(shù)組)(必填)要本地化的數(shù)據(jù)本身。可以是單獨的一個或者多個(WordPress 3.3+)二維數(shù)組。
默認值:無
示例
<?php
wp_enqueue_script( 'some_handle' );
$translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_value' => '10' );
wp_localize_script( 'some_handle', 'object_name', $translation_array );
?>
重要提示: wp_localize_script() 必須在所要附加數(shù)據(jù)的已進行排隊或注冊的腳本的后面調用。它不會將本地化數(shù)據(jù)附加給它后面的腳本文件。
你可以通過下面的方式訪問腳本中的變量:
<script>
alert(object_name.some_string); // alerts 'Some string to translate'
</script>
倡萌注:注意看本例的2段代碼中的“object_name”“some_string”“Some string to translate”是一一對應的。這樣你就該知道如何使用了。
更詳細的示例,請閱讀:如何本地化翻譯 Javascript 中的字符串
注釋:本地化數(shù)據(jù)將以文本的形式傳遞給JavaScript調用,如果你要傳遞整數(shù),你必須使用JavaScript函數(shù) parseInt() :
<script>
FinalZoom = map.getBoundsZoomLevel(bounds)-parseInt(data.a_value); // Call a function that needs an int.
</script>
源文件
wp_localize_script() 位于 wp-includes/functions.wp-scripts.php#L66.
- 原文:http://codex.wordpress.org/Function_Reference/wp_localize_script
- 編譯:倡萌@WordPress大學




