请参阅wp_localize_script()函数。
您必须将您的脚本排入队列,然后本地化(或者更确切地说:将数据作为内联 JavaScript 传递)您想要在 JavaScript 中引用的数据,最后更新您的脚本以引用新本地化的全局对象。请看我下面的例子。
例子
1-将您的脚本排入您的插件中,然后使用wp_localize_script()
. 确保对两个函数调用使用相同的句柄。
<?php
// !! Edit the variables below to suit your plugin
$add_photo_button_handle = 'some_handle';
$add_photo_button_js = plugins_url( '/add_photo_button.js', __FILE__ );
$photo_num = get_option( 'add_photo_button_cnt' ); // Here you fetch the option data.
// Enqueue your script
wp_enqueue_script( $add_photo_button_handle, $add_photo_button_js );
// Set the data you want to pass to your script here
$data = array( 'photo_button_cnt' => $photo_num );
// Localize the script, the 'photo_button_cnt' value will now be accessible as a property in the global 'add_photo_button' object.
wp_localize_script( $add_photo_button_handle, 'add_photo_button', $data );
?>
2-更改脚本以引用本地化对象
<script type="text/javascript">
jQuery(document).ready(function(){
$cnt = 0;
jQuery('#add-photo-button').click(function(){
//============================================
// See how we access the localized object.
//============================================
if($cnt == add_photo_button.photo_button_cnt ){
jQuery('#add-photo-button').prop('disabled', true);
jQuery('#add-photo-button').addClass('disabled');
}
$cnt++;
var current_count = jQuery('input[type="file"]').length;
//var next_count = current_count + 1;
jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');
});
});
</script>