How to display related Posts in WordPress


In this article, we’ll fetch and display the related post from a similar category on the WordPress website. WP_Query class gives the leverage to customize WordPress default response. Displaying related/similar posts will help to engage the user on the website.

Related Post: How to get random Posts in WordPress

Let’s jump to the actual piece of code.

Step 1: The first step is, we have to prepare your query.

<?php

	$related_posts = new WP_Query(array(
		 'category__in' => wp_get_post_categories($post->ID),                      
         'post__not_in' => array($post->ID),
         'orderby' => 'rand',
         'posts_per_page' => 5
    ));
?>

category__in » retrieve the list of categories for a post.

post__not_in » does not include the current post.

orderby » specify the order of the posts.

posts_per_page » fetches the number of records you have specified.

Step 2: Before looping the result, do a check whether the result contains posts or not.

<?php if ($rlated_posts->have_posts()) : ?>

Step 3: If the result contains post, loop through it and display accordingly.

<ul>
    <?php if ($related_posts->have_posts()) : ?>	
        <?php while ($related_posts->have_posts()) : $related_posts->the_post(); ?>		
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>			
        <?php endwhile; ?>
	<?php wp_reset_postdata(); ?>
    <?php else : ?>
    <?php endif; ?>
</ul>

wp_reset_postdata() function restores the $post global to the current post in the main query.

See the complete example.

<h4>Similar Posts</h4>

<?php
    $similar_query = new WP_Query(array(
        'category__in' => wp_get_post_categories($post->ID),                      
        'post__not_in' => array($post->ID),
        'orderby' => 'rand',
        'posts_per_page' => 5
    ));
?>

<ul>
    <?php if ($similar_query->have_posts()) : ?>
        <?php while ($similar_query->have_posts()) : $similar_query->the_post(); ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>                                
        <?php endwhile; ?>
		
        <?php wp_reset_postdata(); ?>
    <?php else : ?>
    <?php endif; ?>
</ul>

Output

How to display related Posts in WordPress

References

  1. WP_Query
  2. wp_reset_postdata()
  3. wp_get_post_categories()

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.