I was thinking about a nicer way to display the categories in my sidebar.
Instead of a plain list style, I’d like to have images / thumbnails show up as well.
Currently I’m using the following:
<?php wp_list_categories('show_last_updated=1&show_count=1&title_li='); ?>
Simply displaying the name/link + post count of each category.
I want to keep, that but also add a thumbnail to it.
I’ve been browsing through this board for answers and also thought about how to do it, but I couldn’t find a solution yet.
I guess I have to create a function that gets the featured image of the latest post in that category. If a post has more categories, that also shouldn’t cause any problems.
Creating a loop with only 1 post in that category and only outputting the thumbnail would be an option, but to set it so that the thumbnail and category match could be a hassle.
I’m sure that there must be a better way to do it.
I’m not looking for a plugin (as I’m sure there are some), I want to hardcode it.
If anybody has a good idea or some advice how to approach this, then please help me out.
Thank you very much!
You can use a custom Walker, the easiest of which in your case is the
Walker_Category
and extend it like so:Now your
wp_list_categories
can utilize that walker by supplying an additionalwalker
argument like so:As you can see we have two additional queries for each category, one to get the latest post, and one to get its featured image, so make sure that this overhead is acknowledged.
If you want to further customize the output you will have to override all of the functionality of
end_el
orstart_el
for theWalker_Category
class.Duplicates
To make sure that no duplicate images are shown you have to do the following things:
So the code would look something like this:
I know you said you wanted to not use a plugin, but I am still going to recommend this: Taxonomy Images
You can always just hardcode it into your functions file.
It adds a nice little interface to the categories for adding a specific images to each category, and supplies some easy ways to get that image on your pages. It also works on custom taxonomies with no problem.
I mention the plugin because, for a project I was working on I was trying your first approach (to just show the featured image of the latest post in that category) but when a particular post was in more than one category, the same image was repeated multiple times and looked funky.
Having an image for each category kept a consistent look. The plugin is easy to use so the client could change the image with no probleem. I also wrote a little if statement in case the client created a new category but failed to add an image so that it then went on to use the thumbnail of the latest post for that category (sort of long-winded but you get the point):