Loading...
WordPress

How to Display Related Posts From Same Category in the Sidebar in WordPress

Here is a simple working way to display related posts from same category in sidebar without plugin in WordPress. For each post you can display related posts (of same category) in the sidebar.

1. Add following code in your wordPress theme’s functions.php file:

function show_related_post() {
	$args = array(
                'category__in' => wp_get_post_categories( get_queried_object_id() ),
                'posts_per_page' => 5,
                'orderby'       => 'rand',
                'post__not_in' => array( get_queried_object_id() )
                );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) : ?> 
	<section id="recent-posts" class="widget widget_recent_entries">		 
        <h2 class="widget-title">Related Articles</h2>
        <ul class="">
        <!-- the loop -->
       <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                 </a>
            </li>
        <?php endwhile; ?>
        <!-- end of the loop -->
        </ul>
	</section>
        <?php wp_reset_postdata(); ?>
     <?php endif; 
} ?>

2. Add the following code in the wp-includes/widgets/class-wp-widget-recent-posts.php file at the beginning of widget function:

public function widget( $args, $instance ) 
// Code to display related posts
 if(!is_home()){
     show_related_post();
 }
...
}

Now open any single post and check sidebar. You will notice Related Posts widget above Recent Posts which will list all related posts from same category. I have also added a condition not to display related posts widget in the home page (as it does not make sense).

If you liked this article or if you have any query, please leave your thoughts in the comment box below.

Share this article with your friends
Leave a Reply

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