WordPress: Load Files on Specific Pages

There are times when we need break our stylesheets and javascript files up into multiple documents.

For me, this happened when a client asked me to add a new section to their WordPress site that had a significantly different design than the others. It made so much sense to create a new stylesheet than to build off the existing one, but it left me with a new problem: how do I serve that stylesheet to that specific section without serving the other stylesheet?

Thankfully, WordPress can load stylesheets and scripts conditionally by using the wp_enqueue function. Yes, this is widely documented, but I had to scour the interwebs for a while before I was able to piece it together.

Why Load Files Conditionally?

WordPress actually suggests that we use wp_enqueue_style and wp_enqueue_script to link stylesheets or javascript files to a website. They don’t give an explanation, but here are a few reasons I will put out there.

It Helps Maintainability

We link certain files in the document <head> and some just before the closing </body> tag. Sometimes we go so far as to link those assets on specific pages. It can be a pain to remember what is linked where. Having everything together in your functions.php file is so much easier.

It Helps Performance

There is a lot of chatter about web performance. In addition to writing code that is clean and efficient, it’s becoming a best practice to only serve the assets a user needs to view the page. Anything more is bloat which causes longer load times and higher data plan bills.

What is wp_enqueue?

Both wp_enqueue_style and wp_enqueue_script is a WordPress hook that loads your stylesheets and javascript files to your site. In other words, it relieves you have having having to link the files up manually in your HTML like this:


  

    
    

    
    

  

  ...

…and instead, links them up for you via your functions.php file.

Using wp_enqueue

Let’s say you have two files:

  • style.css. This one contains CSS that is used globally throughout your site.
  • script.js. This one contains javascript that is used globally throughout your site.

We’re going to assume that all of the styles and all of the scripts in each of these files are needed and used everywhere on your site. Let’s link them up to our site by adding the following to functions.php:

// Call the function
function geoffgraham_scripts_styles() {
  global $wp_styles;

  // Load Stylesheet
  wp_enqueue_style('style.css', get_template_directory_uri().'/path/to/global.css', false ,'1.0', 'all' );

  // Load Scripts
  wp_enqueue_script( 'script', get_template_directory_uri() . '/path/to/scripts.js' );

}

// Hook into the WordPress Function
add_action( 'wp_enqueue_scripts', 'geoffgraham_scripts_styles' );

Calling the Function

I used my name where I called the function, but you can use anything that makes sense to you.

Load the Stylesheet

The wp_enqueue_style function takes five arguments.

  • $handle: The file name of the stylesheet
  • $src: The file path to the stylesheet. Note that I used get_template_directory_uri() to fetch my site’s primary URL, but a relative path works here as well.
  • $deps: Dependencies the file requires in order to work. In most cases, I find this is false and it is an optional argument.
  • $ver: The file version. I honestly never use this and keep it at 1.0. You can let me know if there’s a good reason to keep this updated.
  • $media: This allows you to set the screen that the file is applicable for. It is optional and defaults to “all”, but you could also set it to screen, print, handheld, or any other CSS media type.

Load the Script

The wp_enqueue_script function is nearly the same as its counterpart.

  • $handle: The file name of the file
  • $src: The file path to the file.
  • $deps: Dependencies the file requires in order to work. For example, jQuery might be a dependency in order to work.
  • $ver: The file version.
  • $in_footer: Set this to “true” to inject the file at the bottom of the page and set it to “false” to inject it in the head. Many times, injecting to the bottom will help your page load faster.

How to Load Files Conditionally

OK, so now we know how to load a stylesheet or a script on every page of the site. Let’s shake things up and say that our client has asked us to create a new page on the site that has it’s own unique design and some custom functionality to boot.

To do this, we:

  • Create a new stylesheet called new-styles.css
  • Create a new script file called new-scripts.js

These new files only apply to the new page and nowhere else. Being mindful of performance, we decide to add a conditional statement to our previous function to load the new files only on that specific page.

Here’s what that looks like in our functions.php file:

// Call the function
function geoffgraham_enqueue_stuff() {

  // Specify the conditional tag
  if ( is_page( 'new-page' ) ) {
        
    // If page matches, then load the following files
    wp_enqueue_style('new-styles.css', get_template_directory_uri().'/path/to/new-styles.css', false ,'1.0', 'all' );
    wp_enqueue_script('new-scripts.js', get_template_directory_uri().'/path/to/new-scripts.js', false ,'1.0', 'all' );

   // If the condition tag does not match...
   } else {

   // ...then load the global files instead
    wp_enqueue_style('style.css', get_template_directory_uri().'/path/to/style.css', false ,'1.0', 'all' );
    wp_enqueue_script('scripts.js', get_template_directory_uri().'/path/to/scripts.js', false ,'1.0', 'all' );
  }
}

// Hook into the WordPress Function
add_action( 'wp_enqueue_scripts', 'geoffgraham_enqueue_stuff' );

See what we did? We wrapped the first example in a two part statement that says: if the current page URL slug is /new-page, then load the two new files we created. If not, then load the other ones instead.

WordPress offers a ton of conditional tags we can use to load files in interesting ways. The list is exhaustive, so check all the conditional tags out and see them for yourself.

Conclusion

Hopefully this little post makes it a little easier to see how WordPress provides us with the ability to not just load styles and scripts from one place, but to load them anywhere based on conditions such as specific pages, posts, categories, archives and many other attributes. It has come in handy for me on a number of projects and is now my default for loading any stylesheet or script to a WordPress site.

✏️ Handwritten by Geoff Graham on February 3, 2014

3 Comments

  1. James Bregenzer
    # July 13, 2015

    This wouldn’t work right away… I changed get_template_directory_uri() to get_stylesheet_directory_uri() and this code worked perfectly.

  2. o2bith
    # August 13, 2017

    $ver is if you like take note which version of style are you use.
    If you make changes, you can name 1.1 and create another style file.

  3. rodmontgt
    # May 23, 2018

    this causes fatal error, don’t know why, currently I’m using memphis documents plugin, but that plugin is breaking my theme with its CSS stylesheet, I want the CSS for that plugin only be loaded in one specific page, I’m using my custom functions plugin to load this code because i don’t want to touch the functions.php but don’t work. Could you help me, thanks.

Comments are closed.