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
//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__infinds posts with the first of those tags,post__not_inleaves out the post being viewed, andposts_per_pagesets the limit of five.caller_get_postsis the old, deprecated name ofignore_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 useignore_sticky_postsin new code.- The loop prints each related post as a link using
the_permalink(),the_title_attribute()andthe_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 DATAsits 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
5to show more or fewer posts.
Related articles
- related posts for a custom post type: the same idea using a custom taxonomy term
- related posts chosen in an ACF Relationship field: when you want to pick them by hand
- previous and next post navigation with images: another block for the end of single.php

