The output of <?php the_category(', '); ?>
is
<a href="http://url.com/category/my-category-name/" title="Show all posts under my-category-name" rel="category tag">my-category-name</a>
I would like add a specific class for each category so I could style it in different colours like in this page. What I’m after is:
<a href="http://url.com/category/alpha/" title="Show all posts under alpha" rel="category tag" class="post-category post-category-alpha">alpha</a>
<a href="http://url.com/category/beta/" title="Show all posts under beta" rel="category tag" class="post-category post-category-beta">beta</a>
<a href="http://url.com/category/gamma/" title="Show all posts under gamma" rel="category tag" class="post-category post-category-gamma">gamma</a>
and the style would be:
.post-category {
margin: 0 0.1em;
padding: 0.3em 1em;
color: #fff;
background: #999;
}
.post-category-alpha {
background: #5aba59;
}
.post-category-beta {
background: #4d85d1;
}
.post-category-gamma {
background: #8156a7;
}
The closest I could find was this answer but it’s just for one class and even google didn’t help much.
Maybe changing the code here a bit? Unfortunately I’m not a coder.
Could anyone point me in the right direction, or better suggest a solution here? Thanks.
EDIT Almost there. I changed that function and pasted it in the theme like this
<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
if($categories){
foreach($categories as $category) {
$output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" class="post-category post-category-'what do I put here?'">'.$category->cat_name.'</a>'.$separator;
}
echo trim($output, $separator);
}
?>
What variable do I put after class=”post-category post-category-????”
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:
And then, in your single.php, you need to replate the_category() with:
Your HTML will be like:
And then, in your CSS file, all you need to do is add some style to these classes. For example:
I hope it helps! Have fun coding. 🙂