fbpx

We build websites for you and your business. For more information and questions: +359 877 439 629

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 Smarty Studio
Our greatest passion is to develop websites that are easy to access, handy and function flawlessly. With unstoppable curiosity and enthusiasm we constantly look for new ways to improve our skills and thus our services. And we sincerely have fun with what we do.