When adding CSS or Javascript files to a WordPress theme it should be done via the functions.php file by using either wp_enqueue_style for CSS files, or wp_enqueue_script for JavaScript files. WordPress will automatically add the necessary code to link to the files either before the closing </head> or </body> tag (based on the parameters passed to either function). This will happen on every page of the website, but sometimes this may not be desired. What if you want to conditionally load certain files on certain pages?
Real Example
On this very website I use a JavaScript library called prism.js (it has a JavaScript file & a CSS file) – it is used to style any code snippets that are on a page, like the ones below. I want this website to be as fast & lightweight as possible, so I want to conditionally load them only on pages which require them – pages with code snippets.
In the snippet below I am adding the base CSS file for the theme, plus the prism.css file & the prism.js file. By using this code all three files will be included on every page of the website.
function add_theme_files() {
//Theme style sheet
wp_enqueue_style( 'theme-styles', get_stylesheet_uri() );
wp_enqueue_style( 'prism', get_template_directory_uri() . '/prism.css' );
wp_enqueue_script( 'prism-js', get_template_directory_uri() . '/js/vendor/prism.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'add_theme_files' );
This is not ideal as there are not code snippets on every page – the two Prism library files are not needed all the time. By making use of the WordPress Conditional Tags it is possible to control which pages the Prism library files are added too.
On this website any post with a code snippet is in the ‘Code’ category. Using the in_category conditional tag will allow a check to be carried out to see if the current page being displayed needs the Prism library.
On line 5 in the snippet below I am checking to see if the page is in the ‘Code’ category. If it is, the wp_enqeue_style & wp_enqeue_script statements contained within the if statement are executed. If not, they are ignored.
function add_theme_files() {
//Theme style sheet
wp_enqueue_style( 'theme-styles', get_stylesheet_uri() );
if(in_category('Code')){
wp_enqueue_style( 'prism', get_template_directory_uri() . '/prism.css' );
wp_enqueue_script( 'prism-js', get_template_directory_uri() . '/js/vendor/prism.js', array(), '1.0.0', true );
}
}
add_action( 'wp_enqueue_scripts', 'add_theme_files' );
By using this method, the two Prism library files are only added the the pages that need them.
In this example I am using only one conditional tag (in_category) but there are many more available. Visit the WordPress Conditional Tags Codex page to find out all the ones which you can use.