Display Related Posts in WordPress

How to display related post in WordPress

Displaying useful related post to your visitor will increase more page view and low bounce rate. most of the website admin are not aware of displaying related post. they are killing itself their opportunity of increase page view as a result the entire website will lost more page view and SEO rank too. statistic says visitor will jump to other website within 10 second if they nothing found resourceful. to keep your bounce rate a minimal rate you should start right now showing related post. it can be under post content or inside post content or sidebar.

How to display related post under post?

related post mean the post is under same categories or tag or related under same criteria. visitor will love to read some related content if they found your website as a useful resource. here is the code you need to add your theme functions.php file to display related post under post content

function dartthemes_related_post($content){
  
  $html = '';
  
  // check single post type
  if(is_singular('post')){
    
    // get current post id
    $post_id = get_the_ID();
    //get current post type 
    $post_type = get_post_type( get_the_ID() );	
    
    // get currnet post category 
    $categories = get_the_category();
  
    if(!empty($categories[0]->term_id)){
      
        $tax_query =  array(
               'taxonomy' => 'category',
               'field' => 'id',
               'terms' => $categories[0]->term_id ,
          );
    }

    $args = array(
    'post_type' => array($post_type), 
    'post_status' => 'publish', 
    'post__not_in' => array($post_id), 
    'showposts' => 5,
    'tax_query' => $tax_query,
    );
    
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      
      $html.= "<h2>Realetd post</h2>";
      $html.= "<ul>";
      while ($my_query->have_posts()) : $my_query->the_post();

      $html.= "<li>";
      $html.="<a href='".get_the_permalink()."'  >".get_the_title()."</a>";
      $html.= "</li>";
      endwhile;

      $html.= "</ul>";
    }
    wp_reset_query();
    
  }

  return $content.$html;
  
}

add_filter('the_content','dartthemes_related_post');

you will see the out like bellow screenshot.

Display Related Posts in WordPress