【函式介紹】
wp_localize_script() 是實現 JS 指令碼本地化的函式。
【函式使用】
<?php wp_localize_script( $handle, $object_name, $l10n ); ?>
【引數說明】
$handle
(string) (必須) 載入指令碼的控制程式碼
Default: None
$object_name
(string) (必須)Javascript 物件名稱,可以再 JAvascript 指令碼中使用,例如:
<script> alert(object_name.some_string); // alerts 'Some string to translate' </script>
Default: None
$l10n
(array) (必須) 本地化資料.
Default: None
【函式例項】
例項一:
<?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 ); ?>
你可以再 javascript 中呼叫 object_name 物件
例項二:
function prefix_enqueue_custom_script(){
wp_register_script( 'prefix_custom_script', plugin_dir_url( __FILE__ ) .'js/custom-script.js', array( 'jquery' ) );
wp_enqueue_script( 'prefix_custom_script' );
wp_localize_script( 'prefix_custom_script', 'prefix_object_name', array(
'upload' => __( 'upload', 'textdomain' ),
'remove' => __( 'remove', 'textdomain' )
) );
}
【原始檔】
wp_localize_script() 位於 wp-includes/functions.wp-scripts.php#L66.