[英]What's the 'right' way to add javascript to wordpress?
I have a function in functions.php that is enqueuing my script.js.我在functions.php 中有一个函数正在排队我的script.js。 Everything works fine.一切正常。 But, I only want that script to run on single.php.但是,我只希望该脚本在 single.php 上运行。 Now it is running on every single page.现在它在每一页上运行。 Is there a way to 'control' on what page the script should run on?有没有办法“控制”脚本应该在哪个页面上运行?
My function looks like this:我的函数如下所示:
function mytheme_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/style.css', array(), '1.0.0');
wp_enqueue_script('customjs', get_template_directory_uri() . '/assets/js/script.js', array(), '1.0.0');
}
add_action( 'wp_enqueue_scripts', 'mytheme_script_enqueue' );
You can add an if statement in the function.您可以在函数中添加 if 语句。 See below:见下文:
function mytheme_script_enqueue() {
wp_enqueue_style('customstyle', get_template_directory_uri() . '/style.css', array(), '1.0.0');
if(is_single()){ //or any way to target the page you want
wp_enqueue_script('customjs', get_template_directory_uri() . '/assets/js/script.js', array(), '1.0.0');
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_script_enqueue' );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.