Enqueuing Conditional Styles – The Correct Way

Hey folks,

I am running Sage (8.0.1) on Bedrock (1.3.3). I would like my header to have two sets of styles: one for the home page and one for the rest of the site.

In my pre-Roots/Sage days (i.e. when my themes were a mess) I would simply put an if statement wherever felt appropriate at the time and onwards I’d go. However the beauty of Sage is that it’s teaching me to do things the right way. What is the correct way to conditionally include a .less file, to be enqueued and compiled along with the rest of my styles in main.css? I feel it should be somewhere in /lib/{assets.php} or {config.php}, but I’m just not sure.

Thanks for your help in advance,

Dave.

I haven’t tested, but something like this should do?

Add styles to assets/styles/homepage.less
Add an entry for homepage.css to the dependencies in assets/manifest.json

// lib/assets.php
function assets() {
  wp_enqueue_style('sage_css', asset_path('styles/main.css'), false, null);
  if( is_front_page() ) {
    wp_enqueue_style('homepage', asset_path('styles/homepage.css'), false, null);
  }
}
4 Likes

Do what @mikespainhower said if you want to load different files, but do you need different files? Is it enough CSS that warrants a separate request / file? You could just write your styles in a way that work for both your home page and the rest of your site :slight_smile:

1 Like

Thanks for that @mikespainhower! That will be really helpful for larger stylesheets.

AH @benword, of course – I can use the ‘home’ class on the body to specific rules, right? Can’t believe I missed that one, thanks very much for the help. Is that what you meant, Ben? Interested in another method if one exists.

Cheers!

For sure. You can use classes from the <body> element to target specific pages. You can also write your styles for the home page template in a way that allows you to style them so that doesn’t affect the rest of your site.

So impressed at the support for Roots products. Thanks Ben.

P.s. the last time I was on these forums I mentioned that I had to go back to Roots, as I was having trouble with Sage. Needless to say whatever was going wrong is all fixed now and Sage is running like a dream.

3 Likes