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.