【函數介紹】
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.