WordPress How to: Show related posts without a plugin

How to show related posts without plugin in WordPress

Showing related posts below posts on your WordPress blog or website is very effective in increasing pageviews and increasing visitor time and interaction. You can use a WordPress plugin to show related posts, but you can also copy-paste a custom code to show related posts based on categories. This code checks all categories and shows posts from those categories.

<!--RELATED POSTS-->
<?php
	$original_post = $post;
	$categories = get_the_category($post->ID);
	if ($categories) {
	$category_ids = array();
	foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
	
	$args=array(
		 'category__in' => $category_ids,
	    'post__not_in' => array($post->ID),
	    'showposts' => 10,
	    'order' => 'ASC',
	    'orderby' => 'rand'
	   );
	  $my_query = new WP_Query($args);
	  if( $my_query->have_posts() ) {
	      echo "<div id=\"relatedposts\" class=\"gridview\">";
	      echo "<h3 id=\"relatedtitle\">Related Posts</h3><ul>";
	  
	  while ($my_query->have_posts()) : $my_query->the_post(); ?>
  
		<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
	<?php endwhile;
	
	echo "</ul></div>";
}
}
$post = $original_post;
wp_reset_query();
?>
<!--RELATED POSTS ENDS-->

Paste the above code on “posts” template file at the desired place. You can put thumbnails, exerpts or entire posts in the related posts loop. Use HTML and CSS to style the output.