How to show Related posts by Category in WordPress without any plugins

Most of the blog site or news site shows links to “Related Posts” at the end of the post. Those gathered randomly from the same category as the current post. Today I will show you how to create the query to get posts from the current category. Display a list of random links below your posts without using any plugin.

    $related = new WP_Query(
                        array(
                            'category__in'   => wp_get_post_categories( $post->ID ), // get posts from current post category
                            'posts_per_page' => 5, // how posts shows
                            'orderby'       => 'rand', // order by random
                            'post__not_in'   => array( $post->ID ) // exclude current post from the related posts
                        )
                    );
                    
                    if( $related->have_posts() ) { 
                        while( $related->have_posts() ) { 
                            $related->the_post();
                            // Output (Title, Thumbnail etc)
                   }
             wp_reset_postdata();
       }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: