Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Thanks very much.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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