Get related posts by category

In some cases you need to show related posts with the same category as the current post. Below I will explain you how you can do this.

  1. Get the current post id from the global $post variable.
  2. Get the category of the current post by using my get_first_term_by_id() function.
  3. Create a new object with WP_Query() and set ‘post_type’ to (in my case) ‘post’,  use the tax_query to set the ‘taxonomy’, ‘field’ to ‘id’ and ‘terms’ to the $term_id variable.
  4. Do a while loop with the $related object and echo out the posts.
  5. Reset the post data after the loop with wp_reset_postdata().
global $post;
$post_id = $post->ID;
$term_id = get_first_term_by_id( $post_id, 'category', 'term_id' );
$related = new WP_Query( array(
   'post_type' => 'post',
   'tax_query' => array(
         'taxonomy' => 'category',
         'field' => 'id',
         'terms' => $term_id
if( $related->have_posts() ) {
   while( $related->have_posts() ) {
      echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';