WordPress Related Posts without Plugins

Add Related Posts section in your article is nice for your article reader.

The easy way is to find a plugin to install. and set a little bit to get it.

Here we have another solution, maybe you do not want to install too much plugins in your blog. So you have to change code by yourself.

Open WordPress theme’s single post template. In proper location which you think is good , to paste the following code (you might have to change some code due to your theme and requirement):

 

   1:  <!-- my code start -->
   2:  <br />
   3:  <div>
   4:  <br />
   5:  <span class="postcomment">
   6:  <?php
   7:  /list 5 post titles related to first tag on current post
   8:  $tags = wp_get_post_tags($post->ID);
   9:  if ($tags) {
  10:  ?>
  11:  <h3><?php _e('Related Posts', 'f2') ?> </h3>
  12:  <?php
  13:   $first_tag = $tags[0]->term_id;
  14:   $args=array(
  15:   'tag__in' => array($first_tag),
  16:   'post__not_in' => array($post->ID),
  17:   'showposts'=>5,
  18:   'caller_get_posts'=>1
  19:   );
  20:   $my_query = new WP_Query($args);
  21:   if( $my_query->have_posts() ) {
  22:   while ($my_query->have_posts()) : $my_query->the_post(); ?>
  23:   <h4><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
  24:  <?php the_title(); ?></a></h4>
  25:   <?php
  26:   endwhile;
  27:   }
  28:  }
  29:  ?></span>
  30:  </div>
  31:  <!-- my code end -->