How To Show An Image For Each Category In A WordPress Blog
On 12.14.2008 by Paul Robinson |
So a few people have asked me how I get those little category tabs on the left of each post to show up. Well I’m going to tell you. It actually quite simple & there is probably a better way to do it, but I like my way & it works quite well for being [...]
So a few people have asked me how I get those little category tabs on the left of each post to show up. Well I’m going to tell you. It actually quite simple & there is probably a better way to do it, but I like my way & it works quite well for being so simple.
The CSS
So first of all you need to make a CSS rule for each category that you plan to have an image for. These are mine:
div.post div.news { background: #fff url('images/cat_news.jpg') no-repeat left 20px;}
div.post div.wordpress { background: #fff url('images/cat_wordpress.jpg') no-repeat left 20px;}
div.post div.the_top_lists { background: #fff url('images/cat_the_top_list.jpg') no-repeat left 20px;}
div.post div.coding { background: #fff url('images/cat_coding.jpg') no-repeat left 20px;}
div.post div.gadgets { background: #fff url('images/cat_gadgets.jpg') no-repeat left 20px;}
You need to use a class for each one, since it could be on the page more than once & name it the same as your categories slug. Why the slug? Well they don’t have spaces in them. Next you need a little bit of PHP coding to help the work.
This bit is important. You should have your WordPress loop which looks like this:
while(have_posts()) : the_post();
Underneath that place the following:
$cat = get_the_category();
$cat = $cat[0]->category_nicename;
This will get the slug of the category in question & store it in the variable $cat. Please note that although you can assign more than one variable to a post only the first one WordPress collects will show it’s picture. There’s only one thing left to do and that is to place an echo into the element you want the image to show on. So for example my image is aligned to the left in a div that holds the title of the post. Here is what it looks like:
<div class="title <?php echo $cat; ?>"></div>
That’s it. That should work & it’s exactly how I do mine and as you can see mine is working.
If you have any comments, questions or queries then don’t hesitate to drop me a comment.
Leave a comment