Get Related Post In WordPress

If you want to show related post then there are two methods of doing so and you can choose whichever method you prefer. One way is doing it without a plugin and then there is another method that is doing it with a plugin.

Display Related Posts in WordPress with WP_query()

  • Open your theme function file and put this code into function file.

    <?php
    //This function will print related post. there is two parameters 1st is Post ID 2nd is QTY (Quantity)
    function getRelatedPost($ID,$QTY) {
    
        $tags = wp_get_post_tags($ID);
        if ($tags):
            $first_tag = $tags[0]->term_id;
            $args = array(
                'tag__in' => array($first_tag),
                'post__not_in' => array($ID),
                'showposts' => $QTY,
                'caller_get_posts' => 1
            );
            $my_query = new WP_Query($args);
            if ($my_query->have_posts()):
                $HTML = "";
                while ($my_query->have_posts()) : $my_query->the_post();
                    $HTML .= '<a href="'.the_permalink().'" rel="bookmark" title="'.the_title_attribute().'">'.the_title().'</a>';
                endwhile;
            endif;
            wp_reset_query();
        endif;
        echo $HTML ;
    }
    ?>
    
  • Call this function into your single.php file and pass the post id and post length.
    <?php getRelatedPost($post->ID,'5'); ?>

Display Related Posts in WordPress with plugin

The plugin we use is called Yet Another Related Post Plugin (YARP). It gives you a list of posts and/or pages related to the current entry, introducing the reader to other relevant content on your site. for more details please visit on plugin site.Yet Another Related Post Plugin