Do you want to display or add recent posts of the current category on the side bar of your wordpress blog ? Recently, I added such a column to list down the recent posts of the current category instead of always showing the recent posts from all categories. That’s a very helpful feature because your reader will find more related + recent posts after reading a post.
For example, this current post is on the category “website” so you could see the recent posts from “website”category on the side bar of this blog. Basically, this helps your reader to locate more related content on your blog. I believe this plays a bit of SEO on your blog too because you are linking to related content based on the current category. Such things are easily possible on wordpress blogs.
Okay, lets see how to add such recent posts from the current post’s category on your wordpress blog. The following is the code snipped that checks the current category in “if” condition using the function in_category() and then displays the recent posts title using <h2> tag. The function is_single() is used to check whether the current page is a single post or not. Then it queries the post from that category and displays one-by-one using a “while” loop as anchor text’s using <a> tag.
You have to copy the below code and paste on your sidebar.php or where ever you want. Just you have to replace the category name ‘website’ with your category name and replace the text within <h2> into your’s. It lists the last 15 recent posts that you could change, if required.
<?php if (in_category(‘website’,$wp_query->post->ID) && is_single()) : ?>
<li><h2>Website & Blog Tips – Recents</h2>
<?php query_posts(‘category_name=website&showposts=15’); ?>
<?php while (have_posts()) : the_post(); ?>
<li><a href=”<?php the_permalink() ?>” title=”<?php the_title(); ?>”><?php the_title(); ?></a></li>
<?php endif; ?>
The above code just checks whether the current posts is from the category ‘website’ and displays the recents posts from that same category. So if your blog has 5 such categories you have to paste this code 5 times one after the other & change the category name’s and <h2> title’s. You could get the exact category names from Posts->Categories menu inside your wordpress admin page.
That’s it, you are done. Just save the page and view post’s from different categories on your blog. You should see recent posts based on the current post’s category instead always showing the recent posts from all categories.
This piece of code makes your wordpress blog more readable and search engine friendly. Let me know if you have any doubts in using this code.