Load specific JavaScript on certain WordPress pages

This problem was a pain. I wasted 3 hours trying to figure this one out and thought I share my new found knowledge with you.

The recommended way to add JavaScript is to enqueue it in the functions.php file of your theme. I did that but found that the is_page() function wasn’t working. In fact, when it was in functions.php, wordpress had know idea whether it was a page or not. Lot’s of surfing told me it had to do something with the Loop (as all WordPress does). I wanted JavaScript on my home page that ran an image slideshow but only ran on that page. The rest of the site would use my custom JavaScript page. With is_page() not working what was I to do? Here is my solution.

The secret is wp_print_scripts. This makes sure that WordPress is at a point where it understands this is a page before it is called.


[cc lang=”php”]

Leave a Reply

Your email address will not be published. Required fields are marked *