Of love and slugs

Client: Can we have every post category look different?

A super quick trick today: the client requested that a listing of their wordpress blog posts be color coded with different heading styles to add a sense of excitement to their post page.

The easiest way to go about that would be to create a CSS class based on each category. We would have to achieve the following:

  • Echo the category name to use as a new class
  • Display the category name as a slug (to use in CSS)
  • Create CSS classes
  • Append the category name as the new class to an existing element, like the header

WordPress makes retrieving the category name easy with tags like get_the_category, but those tags output either lists or actual names, rendering a full name of a category like “Party Planning.” That formatting with the space is no use to us in css, we are looking for “party-planning” instead.

That’s when we use the slug instead. Attached is the code used to achieve a dynamically generated CSS class for every post.

<?php
$categories = get_the_category();
$cls = '';

if ( ! empty( $categories ) ) {
  foreach ( $categories as $cat ) {
    $cls .= $cat->slug . ' ';
  }
}
?>

<li class="<?php echo $cls; ?> ">
    <div class="content">
        <h4><?php the_title(); ?></h4>
    </div>
</li>