简体   繁体   English

将 javascript 添加到 wordpress 的“正确”方法是什么?

[英]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.

相关问题 用WordPress编写JavaScript的正确方法是什么? - What is the right way to write JavaScript in WordPress? 什么是导入模块javascript node.js的正确方法 - What's right way to import a module javascript node.js 将这个数据库结果传递给javascript函数的正确方法是什么? - What's the right way to pass this database result into a javascript function? 什么是正确的方法? 用javascript和mysql - What is the right way ? With javascript and mysql 什么是在页面加载后立即运行JavaScript函数而不使对象“跳转”的正确方法 - What's the right way to run a javascript function without getting the object to “jump” right after the page loads 为服务/产品添加百分比的正确方法是什么? - What is the right way to add percentages to a service/product? 将2个javascript对象连接在一起的正确方法是什么? - What is the right way to wire together 2 javascript objects? 用Java搜索网站功能的正确方法是什么? - What is the right way for Searching functions in a Website with Javascript? 在JavaScript中有继承的“正确”方法吗?如果是这样,它是什么? - Is there a “right” way to do inheritance in JavaScript? If so, what is it? 后备和JavaScript同时进行。 正确的方法是什么? - Fallback and JavaScript concurrently. What is the right way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM