Display Related Posts in WordPress

Quick Summary

  • Take the current post's first tag with wp_get_post_tags() and query up to five other posts sharing it, with no plugin needed.
  • Add the code to single.php inside the Loop, preferably in a child theme, for example right after the_content().
  • Replace the deprecated caller_get_posts with ignore_sticky_posts and remove the ACTUAL POST DATA comment line, which prints as text.

This snippet shows up to five related posts on a single post page, based on tags: it takes the current post’s first tag and lists other posts that share it. No plugin is needed. Add it to your theme’s single.php (preferably in a child theme) inside the Loop, for example after the_content().

PHP
<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'posts_per_page'=>5,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>



//ACTUAL POST DATA
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>


 
<?php
endwhile;
}
wp_reset_query();
}
?>

How it works

  • wp_get_post_tags() gets the current post’s tags, sorted by name. If the post has no tags, nothing is shown.
  • tag__in finds posts with the first of those tags, post__not_in leaves out the post being viewed, and posts_per_page sets the limit of five.
  • caller_get_posts is the old, deprecated name of ignore_sticky_posts, which stops sticky posts from being moved to the top of the results. WordPress still accepts it but reports it as deprecated when debugging is on, so use ignore_sticky_posts in new code.
  • The loop prints each related post as a link using the_permalink(), the_title_attribute() and the_title(). wp_reset_query() then restores the main post’s data so the rest of the template works.

Things to adjust

  • The line //ACTUAL POST DATA sits outside the PHP tags, so it prints on the page as text for every related post. Remove it or replace it with your own markup.
  • “Related Posts” is echoed as plain text as soon as the post has tags, even if no related posts are found. Wrap it in a heading, and the links in a list, to fit your design.
  • Change 5 to show more or fewer posts.
Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More