corenominal

Full stack web developer, interested in all the things, but especially the web, code, design, Linux, OS X, PHP, WordPress, JavaScript & robots.

Conditionally include additional CSS and JavaScript for page templates in WordPress

I’m currently working on a large’ish WordPress theme that has a number of custom page templates. The custom page templates require their own CSS and JavaScript files, so I’m using the following code to enqueue the additional files. This allows for a file structure like so:

themes/mytheme/page_template_foo.php // custom page template
themes/mytheme/css/page_template_foo.css // additional CSS
themes/mytheme/js/page_template_foo.js // additional JS

The code should be self-explanatory, but see the comments for explanations as to what’s happening.

Notes: this method increases overheads as it tests for the existence of files, if you’ve only got a couple of custom page templates, you’d be better off hardcoding. That said, if you’re using caching it shouldn’t be a big deal. Also, unless you’re using HTTP/2, you’ll probably want to use something like Autoptimize to concatenate the CSS and JS files.

Leave a comment

Your email address will not be published. Required fields are marked *