Contextually changing your theme's stylesheet
WordPress 2.8 introduced the body_class()
function, which allows you to contextually style elements in your theme’s style.css
. Few themes allowed this sort of functionality before this release.
While it’s cool to be able to style a particular post or page (or tons of other things) with a simple CSS selector in a single stylesheet, it’s not always enough. Sometimes, you may need to drastically change the appearance of a page. To do this, you’d need to load a different stylesheet.
Many tutorials will tell you to dive directly into your theme’s header.php
file. Of course, you know I’m more interested in doing things the smart way by taking advantage of a theme’s functions.php
file. This technique will allow you to easily transfer your custom code from theme to theme, use within a plugin, and it’s the best method when working from a child theme.
Dynamically changing your theme’s stylesheet
For this example, we have two pages we want use separate stylesheets on: About and Portfolio. The first thing you should do is create your stylesheets. Drop them into your theme (or child theme) folder and name them style-about.css
and style-portfolio.css
.
Once that’s done, add this code to your functions.php
file:
<?php
add_filter( 'stylesheet_uri', 'my_stylesheet', 10, 2 );
function my_stylesheet( $stylesheet_uri, $stylesheet_dir_uri ) {
if ( is_page( 'about' ) )
$stylesheet_uri = $stylesheet_dir_uri . '/style-about.css';
elseif ( is_page( 'portfolio' ) )
$stylesheet_uri = $stylesheet_dir_uri . '/style-portfolio.css';
return $stylesheet_uri;
}
?>
Just save and check out your new styles.
The code explained
What we’ve done with the few lines of code above is filter stylesheet_uri
, which is a hook that returns your currently active theme’s stylesheet. This hook gives us two parameters we can use:
$stylesheet_uri
The URI to the current theme's stylesheet, which needs to be returned.$stylesheet_dir_uri
The URI of the current theme's directory, which we can use in our own function and not have to figure out where our styleheets are.
The is_page()
function is one of many conditional tags at your disposal for determining what page a visitor is currently viewing.