2

Does it matter if I enqueue a script on just the page I need it to be used? As opposed to functions.php?

Or, what is the best practice? In this example I need a rotator just on the front page of my site.

And if I do enqueue it on the page, is there a best place to put it?

3

Go with functions.php.

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to problems. See #11526 for details.

Source: http://codex.wordpress.org/Function_Reference/wp_enqueue_script

function themename_load_js() {

    if ( is_admin() ) {
        return;
    }

    if is_page( 123) { // Replace 123 with your page's ID.
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'rotator-js', get_template_directory_uri() . '/js/rotator.js', array ( 'jquery' ) );
        wp_enqueue_script( 'rotator-init-js', get_template_directory_uri() . '/js/rotator-init.js', array ( 'jquery', 'rotator-js' ) );
    }
} 
add_action( 'wp_print_scripts', 'themename_load_js' );

Edit: Bonus tip: Whenever I need to do something like this, rather than hard coding the page ID in the function, I create an options page and add a call to wp_dropdown_pages() which allows the user to choose the special page. You said that you're using the front page, so you could probably leverage is_front_page() within your function rather than checking the page ID, which is even cleaner.

1

This is absolutely working for me right now:

add_action('get_header', function() {
    if(is_page('566')) {

        function sp_enqueue_script() {
            wp_enqueue_script(
                'sp-custom-script',
                get_stylesheet_directory_uri() . '/assets/js/sp_script.js',
                array( 'jquery' ), '1.0', true
            );
        }

        add_action( 'wp_enqueue_scripts', 'sp_enqueue_script' );
    }
});

is_page doesn't work in functions.php because the main query hasn't loaded yet, so wait for the header to load.

Last boolean in the wp_enqueue_script hook is for the script to be enqueued in the footer, so it runs faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.