How To Show Related Posts By Category Without Plugin

  • Post author:
  • Post category:WPDEV
  • Post comments:0 Comments
  • Post last modified:August 11, 2020

In the WordPress plugins repository, you can find various plugins that can help you to show related posts below every post. But you can also display related posts by category without plugin. In this article, I will help you to display related posts with thumbnail from same post without installing a plugin.

Display Related Posts By Category Without Plugin

The following code will search other posts based on the category of current post and display them as related posts with thumbnail.

To make this task easier, I have split it into different steps, so carefully follow every step. 

Step1: Add Related Posts Algorithm in your Theme

Create a “template-parts” folder in your theme and create a related-posts.php file inside the “template-parts” folder. 

Then add the following related posts algorithm in related-posts.php file. 

<div class="two-section-heading cat">
   <div class="row">
	    <div class="col-md-12 col-sm-12 col-xs-12">
           <div class="heading-t-box heading-genral">
                <h4>Related post</h4>

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

<div class="row">
    <div id="related-post">
    	<?php  if( $related->have_posts() ) { 
               while( $related->have_posts() ) {  
        <div class="col-md-4 col-sm-4 col-xs-12">
            <div class="full-width-related">
            	<?php $guff_image = wp_get_attachment_image_src( get_post_thumbnail_id());?>
                <img src="<?php echo esc_url($guff_image[0]); ?>" alt="" class="img-responsive">

                <h1><a href="<?php the_permalink();?>"><?php the_title();?></a> </h1>

Note: You can also add the above algorithm code directly to single.php file without creating a different folder & file. If you choose this method, skip the second step too.

Step2: Add Related Posts Below Every Post

In this step, we will load the related posts algorithm code to single.php file to generate related posts below every post.

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


Related posts with thumbnail


Now it’s your turn to add CSS code to style the related posts section. Give a stylish look to related posts on the basis of your theme. 

If you have any problem while generating recent posts by category in WordPress posts then feel free to start a conversation in the comment box. 

Leave a Reply