|

Quick Tip: Custom Category Styles in WordPress

Over the weekend I revamped this blog’s current theme a little bit, including adding custom styles for my Link Round-up lists. I achieved this by adding a simple piece of code within my loop to make each category a CSS class. Here’s how I did it.

Note: You need to be at least a little bit familiar with the WordPress API, and coding themes.

Go into the theme page where your posts are printed (in most themes, this will be at least 2 places: index.php and single.php) and find The Loop. Here you will either find the div that is wrapping each post or write a div to wrap each post.

For the class, call this function: category_classes() (don’t worry, I’ll provide the code in the next steps). You should have something that looks like this:

<?php while ( have_posts() ) : the_post(); ?>
     <div class="<?=category_classes();?>
          /**You Loop Stuff**/
     </div>
<?php endwhile; ?>

Next, we are going to open up our functions.php and add this function:

function category_classes(){
   global $post;
   $cats= "";
   foreach((get_the_category($post->ID)) as $category) {
      $cats.= $category->category_nicename . ' ';
   }
   return trim($cats);
}

This function grabs the categories of the current post, and adds each of their names (or in this case, the slug to make is a CSS friendly class name) to a string. It returns that string, trimming any extra white space from the ends.

Since we printed it in the first step, now all we have to do is add the CSS. For the WordPress nicenames (or slugs), generally the slug will be all lowercase, where spaces are replaced by dashes (-). So if I have a category called “Quick Tips,” I would define the CSS class .quick-tips.

And there you have it! You can now create different styles for any (or all) of your categories! Just keep in mind, this adds all of the category slugs as css classes, so you may have some conflicts (ie if you have a post in Category A and Category B, you will get class="category-a category-b").

Leave a Reply

Your email address will not be published. Required fields are marked *