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 itmain
,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 thejs
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
- Click on the title of the page you’re interested in to open it in the editor
- 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:
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.
Frequently Asked Questions (FAQs) about Conditional Tags and Loading Styles and Scripts in WordPress
What are conditional tags in WordPress and how do they work?
Conditional tags in WordPress are PHP functions used in theme files to alter the content displayed on a particular page depending on the conditions that the page meets. They are used to determine if a certain condition is met before executing a particular function. For example, you can use a conditional tag to check if a page is a single post before displaying a specific sidebar.
How can I use conditional tags to load styles and scripts in WordPress?
To use conditional tags to load styles and scripts in WordPress, you need to add your scripts and styles in the functions.php file of your theme. You can use the wp_enqueue_script and wp_enqueue_style functions along with a conditional tag. For instance, if you want to load a script only on the homepage, you can use the is_home() conditional tag.
What are some common conditional tags in WordPress?
Some common conditional tags in WordPress include is_single(), is_page(), is_home(), is_front_page(), is_category(), is_tag(), is_author(), among others. Each of these tags checks for a specific condition, such as if a page is a single post, a specific page, the homepage, the front page, a category page, a tag page, or an author page.
How can I create a conditional snippet in WordPress?
To create a conditional snippet in WordPress, you need to use a conditional tag within a PHP if statement. The code within the if statement will only be executed if the condition is met. For example, to display a snippet only on the homepage, you can use the is_home() conditional tag within an if statement.
Why is my style not loading in WordPress?
If your style is not loading in WordPress, it could be due to several reasons. The most common reason is that the style file is not properly enqueued in the functions.php file. Make sure you have used the wp_enqueue_style function correctly. Also, check if the file path and the dependencies are correct. If you are using a conditional tag, make sure the condition is being met.
How can I load conditional CSS the right way in WordPress?
To load conditional CSS in WordPress, you need to enqueue the CSS file in the functions.php file of your theme using the wp_enqueue_style function. You can use a conditional tag to specify the conditions under which the CSS file should be loaded. For example, to load a CSS file only on the homepage, you can use the is_home() conditional tag.
Can I use multiple conditional tags in WordPress?
Yes, you can use multiple conditional tags in WordPress. You can combine them using logical operators like AND (&&) and OR (||). For example, to check if a page is a single post and is not the homepage, you can use the is_single() and !is_home() conditional tags together.
How can I use conditional tags to load different styles for different pages in WordPress?
To load different styles for different pages in WordPress, you can use conditional tags in the functions.php file of your theme. For each style, use the wp_enqueue_style function along with a conditional tag that checks for the specific page. For example, to load a specific style for the homepage and a different style for single posts, you can use the is_home() and is_single() conditional tags.
What is the difference between is_home() and is_front_page() conditional tags in WordPress?
The is_home() conditional tag in WordPress checks if the homepage is being displayed, while the is_front_page() conditional tag checks if the front page is being displayed. If you have set your front page to display your latest posts, then both these tags will return true. However, if you have set a static page as your front page, then is_front_page() will return true for that page, while is_home() will return true for the page set as the posts page.
Can I use conditional tags outside the loop in WordPress?
Yes, you can use conditional tags outside the loop in WordPress. However, some conditional tags, like is_single() and is_page(), might not work as expected when used before the loop. This is because WordPress only knows the specifics of the query after the loop has started. Therefore, it’s generally recommended to use these conditional tags within the loop or after the loop has started.
Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.