Oneupweb : WordPress Quick Tip—Including a JavaScript on a specific page
Ever wanted to load a JavaScript in WordPress, but not have to worry about it being loaded on every page? Fear not! There is an easy solution to this problem!
Let’s say we have a page with the slug “archives” and we have written a revolutionary script to work with that archives page. This is the only page that will be using this script, so we don’t want to waste resources by loading that script on every page, or potentially causing a conflict with a script on another page. Many of you seasoned WordPress developers will be accustomed to something like this in your functions.php file:
add_action('init','load_my_scripts'); function load_my_scripts() { $script = '/path/to/my.js'; wp_enqueue_script('myjs', $script); }
If you try to check for a page during the init action, you will run into some problems. The init action runs before any of the page information is available. The simple solution? Queue your scripts up during the wp_print_scripts action. This is how we would include our “archives” script on just the archives page. In the functions.php file:
add_action('wp_print_scripts','load_my_scripts'); function load_my_scripts() { $script = '/path/to/archives.js'; /******************************* * is_page accepts the page slug,id,or title ********************************/ if ( is_page('archives') ) { wp_enqueue_script('archivesjs', $script); } }
Easy! You can now code happily knowing your scripts are only where they need to be!