Add Related Posts to WordPress without a Plugin

Over the last month I’ve implemented quite a bit of changes to the site, including adding a section to each post that displays links to related posts. I use WordPress for this website and I thought about looking for a plugin that would do the trick. However, I’ve been trying to cut down how many plugins I use to make it easier to upgrade and I came up with an alternative solution that works great.
I decided to add PHP code to the single.php file in the WordPress theme that I use. It goes through all of the tags that were defined for the current post and gets five posts that use the same tag.
I’ve taken the code provided on this website and tweaked it so that it gets the related posts for all of the tags and not just the first one.
<?php
$original_post = $post;
$tags = wp_get_post_tags($post->ID);
if($tags)
{
echo '<h4 class="content-title">Related Posts</h4>';
$sendTags = array();
foreach($tags as $tag)
$sendTags[] = $tag->term_id;
$args = array(
'tag__in' => $sendTags,
'post__not_in' => array($post->ID),
'showposts' => 5,
'caller_get_posts' => 1,
);
$queryDb = new WP_Query($args);
if($queryDb->have_posts())
{
echo '<ul>';
while ($queryDb->have_posts()) {
$queryDb->the_post();
?><li><a href="<?php the_permalink() ?>"
rel="bookmark" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?></a></li><?php
}
echo '</ul>';
}
}
$post = $original_post;
wp_reset_query();
?>
Updated 2/19/2009: I discovered a bug in the original code I posted that caused a problem with the comments. Just add the first line and the last two line to the previous code and it will fix it.
Did you like this article?
Please help us spread the word about this site by tweeting, digging and sharing this article around the web (see the buttons immediately above).
Trackbacks & Pings
Leave a Comment or a Question
Most Popular
Topics
- PHP Programmer Tips(12)
- Project Management(10)
- WordPress Tips(9)
- Work Smarter(8)
- Sample PHP Code(8)
- Programming Advice(3)
Blogroll
