Conditional Tags to Load Styles and Scripts in WordPress

Conditional Loading of Styles and Scripts in WordPress

This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.

If your WordPress website needs a particular stylesheet or JavaScript file only in one specific page or just under a limited number of conditions, there is no need to load those files everywhere on your website.

In this article, you are going to learn how to load CSS styles and scripts only when your website needs them. This way your website will load faster and users who don’t visit the pages with the extra files won’t have to download unnecessary bytes in their browsers.

Why You Should Add Styles and Scripts the WordPress Way

If there is an anti-pattern in WordPress development, it’s adding a <link> and <script> tag to load stylesheets and JavaScript files respectively in the <head> section of the HTML document and calling it a day.

Running a WordPress website involves using stylesheets and JavaScript code that comes from the software itself, a number of plugins, and the active theme.

This means that theme or plugin authors don’t know in advance which styles and scripts a specific installation is going to run, or in which order those resources are needed. For instance, let’s take the jQuery library. This library can be used by WordPress itself to handle Ajax requests and other tasks, by more than one plugin, and by the active theme.

If plugin and theme authors include the stylesheets and scripts they need by adding the appropriate tags directly inside the HTML document, this could open the doors to the possibility of conflicts, of resources being loaded multiple times and/or in the wrong order.

This is why you should always load styles and scripts following best practices as recommended by WordPress.org coding standards:

So that everything works harmoniously, it’s important that theme and plugins load scripts and stylesheets using the standard WordPress method. This will ensure the site remains efficient and that there are no incompatibility issues.

Including CSS & JavaScript — Theme Handbook

How to Use wp_enqueue_style and wp_enqueue_script

The barebones function to include your custom stylesheet into a theme looks like this:

wp_enqueue_style( $handle, $src, $deps, $ver, $media );

Only the first two parameters are obligatory, the others are optional.

  • The $handle parameter is the name of your stylesheet. You can call it main, portfolio, etc., depending on what the file is for. If you’re including stylesheets from a JavaScript plugin, just use the plugin’s name
  • $src stands for the URL where the stylesheet is located
  • The $deps parameter specifies if this stylesheet depends on another stylesheet to work correctly
  • $ver determines the stylesheet’s version number
  • $media stands for the media type the stylesheet is for, e.g., all, screen, print, etc.

As an example, the code to add a stylesheet named portfolio.css to your WordPress website could look like this:

wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen');

To include a JavaScript file, you should use:

wp_enqueue_script($handle, $src, $deps, $ver, $in_footer)

The parameters are similar to those in wp_enqueue_style, except for the last one, which sets a true or false value according to whether you want to place the <script> tag in the <footer> or <header> section of your document.

Let’s say you’d like to add portfolio.js to your website, here’s what the code would look like:

wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true);

This code tells WordPress that:

  • You want to use the portfolio file, which is located in the js subfolder inside the active theme’s directory
  • WordPress needs to download jQuery before loading portfolio.js otherwise the latter won’t work correctly (you don’t need to import jQuery because it already comes bundled with WordPress by default)
  • WordPress needs to add this file in the <footer> section of the HTML document.

It’s likely you want to include more than one stylesheet or script file, in this case wrap all the calls to wp_enqueue_style() and wp_enqueue_script() inside a function and then hook this function to the appropriate WordPress action hook.

Here’s an example. If you’re developing a WordPress theme, you can add this to your functions.php file.

function mytheme_styles_scripts() {
  //main stylesheet, style.css
  wp_enqueue_style( 'style', get_stylesheet_uri() );
 
  //stylesheet for portfolio section 
  //(different from the rest of the site)
  wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen');
 
  //JS for portfolio section
  wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true);  
} 

//hook the function to wp_enqueue_scripts action hook
add_action( 'wp_enqueue_scripts', 'mytheme_styles_scripts' );

Now you can rest assured that WordPress will find all the required stylesheets and scripts and download them in the correct order.

Conditional Loading of Stylesheets and Scripts

The code above works great and follows WordPress best practices. However, WordPress will download portfolio.css and portfolio.js everywhere on your website. If your visitors never go to your porfolio page, which is unfortunate but can happen, the browser would have loaded two unnecessary files.

Now, let’s take it up a notch and make sure WordPress includes portfolio.css and portfolio.js only when visitors land on your portfolio section.

WordPress Conditional Tags

WordPress offers conditional tags, which in combination with regular if...else statements, make it very easy to choose what code to apply under certain conditions.

For example, if you want to execute some code only on the home page of your website and another bit of code everywhere else, then you’ll write something like this:

if ( is_front_page() ):
  //your code here
else:
  //alternative code here
endif;

Conversely, if you want to execute some code everywhere except on the home page of your website, you’ll write:

if ( !is_front_page() ):
  //your code here;
endif;

WordPress offers tons of conditional tags, you can check out a complete list on the Conditional Tags chapter of the Theme Handbook.

There’s a way you can leverage conditional tags to ensure WordPress downloads both porfolio.css and portfolio.js only if visitors access the portfolio page of your website.

Let’s examine some of the ways you can do just that.

Using the Page ID

You can use conditional tags to check if users are on the portfolio page of your website using the portfolio page ID.

To know the page ID do the following:

  • Login to your WordPress website’s Admin panel
  • Click on Pages to access the list of all the pages on your website

    Pages menu in WordPress Admin panel
  • Click on the title of the page you’re interested in to open it in the editor
    Select the page whose ID you want to know from the list of all the pages in the Admin panel of your WordPress install.
  • Now that the page is open in the editor, look at the URL in your browser’s address bar. You should see something like post= plus a number. That number is the page ID:

    WordPress page id in browser's address bar.

Now that you know your page ID, you can modify the previous code that included your theme’s stylesheets and scripts with the use of conditional tags as follows:

function mytheme_styles_scripts() {
  //main stylesheet, style.css
  wp_enqueue_style( 'style', get_stylesheet_uri() );
 
  //check we are on page with ID 1 
  if ( is_page('1') ):
   
    //if we are, load styles and script 
    //for portfolio page
    wp_enqueue_style( 'portfolio', get_template_directory_uri() . '/css/portfolio.css',false,null,'screen');
 
    //JS for portfolio section
    wp_enqueue_script( 'portfolio', get_template_directory_uri() . '/js/portfolio.js', array ( 'jquery' ), null, true);
  endif;  
} 

//hook the function to wp_enqueue_scripts action hook
add_action( 'wp_enqueue_scripts', 'mytheme_styles_scripts' );

Using the Page Title

Conditional tags for pages work with the page title too. If your portfolio page has a title of My Portfolio, the code could look like this (I just add the conditional part for brevity’s sake):

if ( is_page('My Portfolio') ): 
  //rest of the code here 
  
endif;

Using the Page Slug

You can use conditional tags with the page slug, which is the user friendly URL for that page. Here’s what it would look like in practice:

if ( is_page('my-portfolio') ): 
  //rest of the code here 
  
endif;

Conclusion

In this article I discussed how you can include stylesheets and script files conditionally in your WordPress website. There are circumstances when the extra styles are so few in number that it doesn’t make much sense to have a dedicated stylesheet for them. This would only generate one more HTTP request your website could perhaps do without.

However, under appropriate conditions, e.g., a page or topic area with a different design from the rest of the website, selective loading of stylesheets and scripts follows WordPress best practices and ensures your visitors’ browsers only download the amount of data needed to display the requested content.

How do you include custom scripts and styles into your WordPress website? Hit the comment box below to share.

Login or Create Account to Comment
Login Create Account