Conditionally Enqueue a Stylesheet into WordPress for a Certain Page
June 5, 2015



WordPress-Logo

In a recent project I found myself creating an online registration form for a dance competition website. I wanted to use Foundation to style the form, but I only wanted the stylesheet to be enqueued on that one page. Basically I wanted to conditionally enqueue a stylesheet into WordPress for a certain page and only for that page.

I found that there are a variety of different ways to ensure that a stylesheet is only enqueued for one page – so I wanted to create this posts to go over all the different ways I’ve found. If you know any other ways please let me know in the comments below.

First let’s take a look at the code I used. This code was added to a child theme’s functions.php, but if you were creating your own theme you could of course include this in the main functions.php file. The code is a very basic enqueue with the addition of a call to the is_page_template( … ) function. This function will check to see if a page is using a certain template (which is what I used). If it is then it will enqueue the stylesheet:

I think it’s a good thing to note that if you were doing this on a theme of your own creation this could all just be bundled in your main enqueue call, there is no need to create a separate function. To illustrate this I will use the Underscores theme as an example:

As you can see, I’ve simply added the code to the same function where all the other stylesheets and scripts get enqueued and it will work just fine. I just wanted to make sure I went over this to ensure people aren’t making functions for every single stylesheet, I just did added a new function in my code example because I was working with a child theme.

Let’s say that instead you want to include the stylesheet for only one page with a particular ID rather than all pages with a certain template. To do this, change your code to:

Changing is_page_template( … ) to is_page( ’28’ ) will change the check to the page with an ID of 28 (this is assuming that is the ID of the page you want to use. The is_page( … ) function can also take in a post title, post name (slug) or an array containing an ID, post title and post slug to check against:

These two functions (is_page_template( … ) and is_page( … )) should be enough to solve almost any enqueuing problem you may be facing in your own project. I really like using templates and enqueuing based on them (it just seems logical and less hack-y to me) but some instances will require you to use a specific ID etc…

As always thank you for reading and please share it around as much as you can! Please feel free to put any suggestions or ideas for future tutorials in the comments section below.


Comments