Custom conditional statements around your WordPress enqueued stylesheets

Add custom conditional statement code snippet screenshot
Standard

You may be aware that you can add conditional statements around your WordPress enqueued CSS styles (such as <!--[if gt IE 7]><link .../><![endif]-->) to load the script for certain versions of Internet Explorer.

As handy as this is, it doesn’t cater for all situations. This tutorial will show you how you can expand WordPress to add any type of conditional around your enqueued CSS styles.

Lets start with a scenario. We have two scripts enqueued, one is for some styles that should only load for Internet Explorer 8 (IE8) and later, but it should also load for all modern browsers. The other script is for Google Fonts that we are already loading with JavaScript:

WordPress gives us the handy wp_style_add_data() function to add default IE conditionals around our styles, however these do not allow the type of conditional ‘hack’ we need to let our stylesheet render for IE8+ and all modern browsers:

As you can see, the code above will load the stylesheet for older versions of IE only, but it will still be commented out for modern browsers.

Introducing the style_loader_tag hook! Using this hook we can wrap custom conditional statements around any of our enqueued CSS stylesheets. So to put in the IE8+ and modern browsers, we would simply add the following code:

And if we want to do something a little different? Lets say we are loading our Google Fonts via JavaScript, but we want a <noscript> fallback so our fonts still render when JavaScript is turned off? Simple, here is an example of a <noscript> custom conditional statement:

There we go, easy custom conditional statements around WordPress enqueued CSS stylesheets!

Matt Watson

Technical Lead at Make Do
Matt Watson is the co-founder and technical lead of WordPress agency Make Do. Matt loves writing and learning about code, and considers himself lucky to be doing what he loves for a living. Find out more about Matt, or get in touch to hire Matt for your project.

Leave a Reply