Skip to Content

Display Related Posts in WordPress Without a Plugin

|WordPress|0 Comments

Adding links within articles to related posts is a great way to polish the SEO on your WordPress site, but at times It can be redundant, time consuming and hard to remember what articles are related.
So why now automate it!? Here is a great way to do so by displaying a non obtrusive list of related posts. Simply paste this below the content area of your article in single.php or whatever template file your single posts are reading from.

By the way, this code is taken and tweaked a little from:? How to Display Related Posts in WordPress on Wp Beginner.

<?php
//basic list of 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
		  $first_tag = $tags[0]->term_id;
		  $args = array(
			  'tag__in' => array($first_tag),
			  'post__not_in' => array($post->ID),
			  'posts_per_page' => 5,
			  'caller_get_posts' => 1
		  );
		  $my_query = new WP_Query($args);

		  if ($my_query->have_posts()) {
			  echo '<p>Related Posts: ';
			  $post_count = $my_query->found_posts;
			  $i = 1;
			  while ($my_query->have_posts()) : $my_query->the_post();
		  ?>
				  <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><?php echo ($i < $post_count ?  ', ' : ''); ?>
				  <?php
					$i++;
			  endwhile;
			  echo '</p>';
			}
		  wp_reset_query();
		}
?>

If all is well, it should look something like this:

Related Posts in WordPress Without a Plugin

Related Posts

Share This

Related Tags

no comments yet but open for them

Post a Reply

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