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

by emuslearner
0 comment

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();
       }
0 comment

More Posts in this topic

Leave a Comment

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

//onvictinitor.com/afu.php?zoneid=3046762
%d bloggers like this: