We build websites for you and your business. For more information and questions:  +359 876 700 417

How to display related posts in WordPress without plugins

28.01.2018

How to display related posts in WordPress without plugins

If you are not interested in installing a related posts plugin on your website, you can manually add related posts functionality to your WordPress theme.

To add the functionality manually, you will have to create related-posts.php file in your WordPress child theme and add the following code:

IMPORTANT: Aways use a child theme in WordPress!

<div class="related-posts">		
<?php 
 /**
   * pll_current_language($value) - returns the current language on frontend (Polylang plugin).
   * $value - (optional) either name or locale or slug. 
   * Defaults to slug.
   */
   if (pll_current_language() == 'en') { 
      echo '<h3>You might also like</h3>';
   }

   $related = new WP_Query(
      array(
	 'category__in'   => wp_get_post_categories( $post->ID ),
	 'posts_per_page' => 3,
	 'post__not_in'   => array( $post->ID )
      )
   );

   if( $related->have_posts() ) { 
      while( $related->have_posts() ) { 
	 $related->the_post(); ?>
	 <div class="related-posts-link">		
	     <a rel="external" href="<?php the_permalink();?>"><?php the_title(); ?></a>		
	 </div><?php 
      }
      wp_reset_postdata();
   }	
?>
</div>

Then, in single.php file of your theme add the code below in place, you want to show related posts:

<?php get_template_part('related', 'posts'); // related posts ?>

You can use this code anywhere in the single.php file of your theme. But we recommend adding it right after your content. Most themes wrap the main content of the post in a <article> tag. To display related posts after the contents of your posts, paste the above code after </article> tag of your single.php file.

Now, add the following code to your style.css file:

div.related-posts  {
   margin-top: 30px;
}

div.related-posts-link {
   text-transform: uppercase;
   padding: 5px 0;
}

The above code will handle the design part of the related posts displayed below your posts.

Remember: The PHP code snippet will pull posts related to the same category as used by the current post.

Now go and code your way to the related posts display. You can do it!

Programming, Tips and Tricks, WordPress ,
About Martin Nestorov
I dedicated 5 years of my life to history. I’ve never known that soon after university graduation I would find my one and only true passion – web development and programming.