I’ve spent the best part of this morning working out how to add a post’s category to its h2 tag’s class – which then allows me to do category-specific styling. Essentially I wanted each headline to be a different colour based on its category – simple result, slightly convoluted solution.
Anyways, it took a while so I thought I’d share it here to save others the hassle!
You first need to add the following to your functions.php file
<?php
function the_category_unlinked($separator = ‘ ‘) {
$categories = (array) get_the_category();
$thelist = ”;
foreach($categories as $category) { // concate
$thelist .= $separator . $category->category_nicename;
}
echo $thelist;
}
?>
Basically this takes the results of the usual the_category() query – i.e. an unordered list – and strips out all the list formatting and presents the results as a nice list of the categories, with each category separated by a space.
You can then add this to your h2 (or whatever tag you want to style) class=”ADD HERE” in your index.php file (or wherever you need)
<?php the_category_unlinked(‘ ‘); ?>
This pulls the category info as formatted by the function you just wrote in the functions.php file – i.e. without any list formatting.
You then just need to add the relevant class styling info (e.g. .categoryname{some styling}) to your styles.css file and you’re good to go.
Hopefully this was useful.