How To: Change CSS Styles with Different Categories in WordPress (using in_category)

The problem

Recently I needed to set up WordPress to change the background colour of the page with each parent category. After a bit of Googling, it appeared no-one had an easy answer, so I turned to my good friend the if statement. I thought I’d combine an if statement with the WordPress template tag is_category. Soon turned out that that wasn’t an option; the is_category template tag only works for archive pages, not posts themselves.

The solution

The solution was another template tag, in_category. Combine that with a number of different CSS files, each with a different colour, and I was left with the following:

<link rel="stylesheet" href="<?php bloginfo('template_url')?>/blue.css" type="text/css" media="screen,projection" />

if( in_category( 1 ) )
<link rel="stylesheet" href="<?php bloginfo('template_url')?>/blue.css" type="text/css" media="screen" />	

<?php } elseif ( in_category (2) )
<link rel="stylesheet" href="<?php bloginfo('template_url')?>/yellow.css" type="text/css" media="screen" />

<?php } elseif ( in_category (33) )
<link rel="stylesheet" href="<?php bloginfo('template_url')?>/black.css" type="text/css" media="screen" />
<?php }	else { 	?>

<?php }	?>

And that’s it. Obviously, you’ll need to put the code in the header.php file and have these different stylesheets created/