There are situations that may arise where you want to load a JavaScript file only on a certain page or pages instead of loading it on every page of the website, primarily because you only want it to run on that page and don’t need it to load on pages where it is not running. Most WordPress themes enqueue (load) their necessary scripts on all pages already, but what if you want to conditionally enqueue scripts or a script instead? This quick tutorial will show you how to do that – to check if you are on a certain page or pages and, if so, load the corresponding script file.
WordPress has an abundance of conditional tags built in. Utilizing these to match the conditions you’re looking for, you can wrap the enqueuing of your script so that it only loads when the condition is met. For instance, if you only wanted the script to run on a page with the slug of ‘mypage’, you would use the conditional tag if(is_page('mypage')) { load that script! } to conditionally enqueue your script only on that page.
Of course, there are a multitude of other conditional tags you can use, found at the link above. Some more common uses may be:
So let’s move on to how to use these tags to conditionally enqueue scripts in WordPress. Simply open your theme’s functions.php file and add the following code at the bottom.
[php] add_action('wp_enqueue_scripts', 'firstwd_enqueue'); function firstwd_enqueue() { if (is_page('mypage')) { wp_enqueue_script('script-name', get_template_directory_uri().'/path-to-script-name.js', array( 'jquery' ), '', true); } } [/php]
You will need to make sure to change ‘mypage’ to the slug of your page, ‘script-name’ to whatever you want to use as a unique name of the script, and ‘/path-to-name-of-script’ to match the url to the script within your theme’s directory (often something like ‘/assets/js/name-of-script.js’).
Again, refer to the WordPress Codex for all of the variations of tags that you can use to conditionally enqueue scripts in WordPress.