Style Links with CSS by Category – WordPress

A recent WordPress project required having a recent posts widget that each link was styled differently with CSS based on what category the post came from. A bit of a jargon loaded sentence I admit.

Basically, if a “recent post” link in this widget was from the “Tools” category (for instance) then it could be styled with a CSS background image or a color specific to that category.

I ended up modifying this Recent Posts plugin. (In enhanced-recent-posts/includes/plugin-class.php line 161)

Here is what I ended up using:

116
<a class="<?php $category = get_the_category();  echo $category[0]->category_nicename; ?>" href="</pre"></a>

Here is what it then looked like when the code worked it’s magic:

<a class="tool-category" href="...</pre"></a>

This WordPress function for getting the category was very helpful.

Have a better way to style links with CSS by category? Bonus if there is a plugin already doing this.