Display related Posts

There are many plugins that let you display related Posts. Some are obviously better than others – but you don’t really need a plugin to do the job. You can add some lines of code to your Template, which will display related Posts based on similar Tags or Categories.

I will show you two options; displaying related Posts based on either Tags or Categories. Put the code in your single.php where you want to display related Posts. Right above <?php comments_template(); ?> is probably the best place.

The following will display the five most recent Posts which share the same first Tag of the Post:

<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
	$first_tag = $tags[0]->name;
	$args = array(
		'numberposts' => 5,
		'tag' => $first_tag,
		'exclude' => $post->ID
	);
	$related = get_posts($args);
	if($related) {
		echo <div id="relatedposts">';
		echo <h4>Related Posts</h4>';
	  	echo<ul>';
		  foreach ( $related as $rel ):
			echo <li><a href="'. get_permalink($rel->ID) .'" rel="bookmark" title="Permanent Link to '. $rel->post_title .'">'. $rel->post_title .</a></li>';
		  endforeach;
	    echo </ul>';
	    echo </div>';
 	 }
}
?>

If you don’t use Tags, or simply just want to find related Posts based on Category, the following code will do that – displaying the five most recent Posts from the first Category of the Post.

<?php
$cats = get_the_category();
if ($cats) {
	$first_cat = $cats[0]->cat_ID;
	$args = array(
		'numberposts' => 5,
		'category' => $first_cat,
		'exclude' => $post->ID,
	);
	$related = get_posts($args);
	if($related) {
		echo '<div id="relatedposts">';
		echo '<h4>Related Posts</h4>';
	  	echo'<ul>';
		  foreach ( $related as $rel ):
			echo '<li><a href="'. get_permalink($rel->ID) .'" rel="bookmark" title="Permanent Link to '. $rel->post_title .'">'. $rel->post_title .'</a></li>';
		  endforeach;
	    echo '</ul>';
	    echo '</div>';
 	 }
}
?>

The upshot of using this method, as opposed to a plugin, is that you have complete control and can display and style the related Posts as you see fit.

2 thoughts on “Display related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *