Add multiple classes. Different style for each category tag

In order to add an specific class to each category using the_category, you need to hack your code a little bit.

It will output the same result, but with a class added to each item. The class name will be the category slug.

In your functions.php:

add_filter('wp_list_categories', 'add_slug_class_wp_list_categories');
function add_slug_class_wp_list_categories($list) {

    $cats = get_categories('hide_empty=0');
    foreach($cats as $cat) {
        $find = 'cat-item-' . $cat->term_id . '"';
        $replace="cat-item-" . $cat->slug . ' cat-item-' . $cat->term_id . '"';
        $list = str_replace( $find, $replace, $list );
        $find = 'cat-item-' . $cat->term_id . ' ';
        $replace="cat-item-" . $cat->slug . ' cat-item-' . $cat->term_id . ' ';
        $list = str_replace( $find, $replace, $list );
    }

    return $list;
}

And then, in your single.php, you need to replate the_category() with:

<?php 
    $sep = '';
    foreach ((get_the_category()) as $cat) {
        echo $sep . '<a href="' . get_category_link($cat->term_id) . '"  class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '">' . $cat->cat_name . '</a>';
        $sep = ', ';
    }
?>

Your HTML will be like:

<a class="category-slug" href="#">category 1</a> <a class="category-slug-2" href="#">category 2</a>

And then, in your CSS file, all you need to do is add some style to these classes. For example:

.category-slug{color: #000;}
.category-slug-2{color: #FFF;}

I hope it helps! Have fun coding. 🙂

error code: 523