Sep 09 2008
WordPress Related Posts in Sidebar
Several of you keep pestering me on how I do my ‘related posts’ thing in the sidebar. You’re nosy buggers, I’ll give you that. Anyway, here comes the confession part: they’re not really “related” posts at all. In fact, the only thing that they each have in common is that they’re in the same category. My related posts are the last 5 posts from each category that the post you’re viewing is in (whew, mouthful).
In sidebar.php, I check that the post is exactly that: a single post. I can then grab the category IDs, loop through them, and grab the post information as I go. Blah blah blah, the interesting (working) part is:
if (is_single()) {
if (get_the_category()) {
?>
<p>These similar posts from the same categories may be of interest to you:</p>
<?php
foreach((get_the_category()) as $category) {
echo '<h3>Related Posts in '.$category->cat_name.'</h3>'."\r\n<ul>";
query_posts('cat='.$category->cat_ID.'&limit=10');
while (have_posts()) {
the_post();
?>
<li><a href="<?php the_permalink() ?>" title="permalink to <?php the_title() ?>"><?php the_title() ?></a></li>
<?php
}
echo "</ul>\r\n";
}
}
}
You’re all welcome to help yourself, of course.
12 Responses so far
-
Thanks for sharing. How might the current post be excluded from the list? For example, the sidebar of this post lists this very post as a “related post”.
-
@Josh You could probably compare the ID of the post in the loop to that of the post on the page. If they are the same you can skip that once around in the loop with continue. :)
I don’t know how you’ll be able to code that, but that’s probably what you’re aiming for.
-
You can change the query to, query_posts(‘cat=’.$category->cat_ID.’&limit=10&offset=1′);
I’m pretty sure that will work. ;)
-
Hmm..
Youd expect something like:
query_posts(‘cat’=’.$category->cat_ID.’&id=-’.$post->id.’=&limit=10′);
would work, however it doesnt.Perhaps you should patch it so it does then commit it back to wordpress’s trunk.
(or I will :P) -
Finally!
Thank you for this. I’ve tried plugins and other codes, but they always phail. I will be forever grateful. Or at least grateful for a few days.
-
Hi Jem, perhaps you could add these mini tutorials onto your tutorialtastic website. Speaking of that website when are you going to add some more tutorials :)
-
[...] you checked out the comments on yesterday’s post — WordPress Related Posts in Sidebar — you’d have noticed that the “related” posts code I use was flawed. [...]
-
So good! It can be a widget.
I think I will do it
thanks Jem!









