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.

15 thoughts on “Add Related Posts to WordPress without a Plugin

  1. Thanks so much for this code. After trying several hours to implement similar codes from other sites, yours was the only accurate. Kudos! I posted and linked to you.

    Question: How can I add a test if there is no related posts?
    Thanks again!

    Like

    • Thanks for reply. This is probably great tip from you, but I dont understand very well PHP programming, so, I dont know how to do it. Whenever, if you write this in the future, appriciated! Thanks in advance. I follow this topic.

      Like

  2. As i am not much good in PHP i was searching this script for my blog and i finally got it here thank you i will follow the topic thanx once again

    Like

Comments are closed.