如果要添加依赖于jQuery的内联脚本,最好且正确的方法是使用wp_enqeue_scripts
行动挂钩,或wp_footer
, 视情况而定,结合wp_script_is()
功能:
add_action( \'wp_footer\', \'cyb_print_inline_script\' );
function cyb_print_inline_script() {
//Check that jQuery has been printed
if ( wp_script_is( \'jquery\', \'done\' ) ) {
?>
<script>
// js code goes here
</script>
<?php
}
}
但最终可能会出现问题,因为您没有正确管理部门。真正正确的方法是
not print inline scripts that has dependencies. 相反,将其放入文件队列中。
add_action( \'wp_enqueue_scripts\', \'cyb_enqueue_scripts\' );
function cyb_enqueue_scripts() {
wp_enqueue_script(
//Name to handle your script
\'my-script-handle\',
//URL to the script file
get_stylesheet_directory_uri() . \'/my-script.js\',
//Set the dependencies
array( \'jquery\' ),
//Version
\'1.0\',
//In footer: true to print the script in footer, false to print it on head
true
);
}
如果需要将变量传递给脚本,请使用
wp_localize_script
具体如下:
add_action( \'wp_enqeue_scripts\', \'cyb_enqueue_scripts\' );
function cyb_enqueue_scripts() {
//Register the js file
wp_register_script(
//Name to handle your script
\'my-script-handle\',
//URL to the script file
get_stylesheet_directory_uri() . \'/my-script.js\',
//Set the dependencies
array( \'jquery\' ),
//Version
\'1.0\',
//In footer: true to print the script in footer, false to print it on head
true
);
//Localize the needed variables
$script_vars = array(
\'some_var\' => \'some value\',
\'another_var\' => \'another value\'
);
wp_localize_script( \'my-script-handle\', \'object_name_passed_to_script\', $script_vars );
//Enqueue the script
wp_enqueue_script(\'my-script-handle\');
}