简体   繁体   中英

What's the 'right' way to add javascript to wordpress?

I have a function in functions.php that is enqueuing my script.js. Everything works fine. But, I only want that script to run on 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. 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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM