Post Pic

How to: Show related posts without a plugin

Displaying related posts is a very great way to help visitors staying longer on your blog. You can use a plugin, but you also can use tags and a custom code to show related posts. Let’s see how to do!

This code will display related posts based on the current post tag(s). It must be pasted within the loop.

<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
  echo 'Related Posts';
  $first_tag = $tags[0]->term_id;
  $args=array(
    'tag__in' => array($first_tag),
    'post__not_in' => array($post->ID),
    'showposts'=>5,
    'caller_get_posts'=>1
   );
  $my_query = new WP_Query($args);
  if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
      <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>
      <?php
    endwhile;
  }
}
?>

Thanks to MichaelH for this awesome piece of code!

9 Responses

Aug 10 2011 17:41

Not work on WordPress 3.2.1 :)

Aug 27 2011 04:52

As of today, it’s working great with my site.
Oh, and I’m using WordPress 3.2.1.
Thanks!

Now, if only it would show a thumbnail of each post, it’d be 100%.

Sep 02 2011 01:31

You can use thumbnail by including this in your loop:

Sep 12 2011 14:40

Sorry – that code has come out completely messed up.
you can see the full text at
http://photos-for-you.com/single.php.txt

Oct 10 2011 15:36

Thanks for the great piece of code! Via the WordPress forum, I found some extra code to adapt it for showing multiple tags. However, I’m running into a problem I cannot fix: I’m using posts with several tags. The effect is that some posts are turning up twice in the results. I’ve checked the loop page on WordPress, but cannot get the code right. Do you have any idea on how I can fix this? You can see the code I’m using here:
http://pastebin.com/QaUjX1u5

Oct 26 2011 18:21

Why only with Tags? Why not with categories? I mean, if anyone can update the code to display related posts by category, would appreciate it a lot. Thanks for any help you can provide.

Nov 30 2011 13:06

Not work on WordPress 3.2.1 – +1

Dec 09 2011 05:41

It does not work in the latest version of WP

Dec 09 2011 16:59

You should add wp_reset_query(); at the end to reset custom loop created and back to the main loop.

This snippet works fine on WordPress 3.2.1. Make sure you put it in the loop.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required