How to Show Related Posts by Category in WordPress
Displaying related posts helps keep visitors engaged by showing them more content they might like. One of the most common approaches is to display posts from the same category as the current post. You can implement this feature using a custom query in your theme’s template files.
Step 1: Add the Related Posts Code to single.php
Edit your theme’s single.php file (or a child theme template) and insert the following code where you want related posts to appear, usually after the content:
<?php
// Get current post ID and categories
$current_id = get_the_ID();
$categories = wp_get_post_categories($current_id);
if ($categories) {
$args = array(
'category__in' => $categories, // Match categories
'post__not_in' => array($current_id), // Exclude current post
'posts_per_page' => 3, // Number of related posts
);
$related = new WP_Query($args);
if ($related->have_posts()) {
echo '<div class="related-posts">';
echo '<h3>Related Posts</h3>';
echo '<ul>';
while ($related->have_posts()) {
$related->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
echo '</div>';
}
wp_reset_postdata();
}
?>
Step 2: Style the Related Posts Section
Add some CSS to your theme’s stylesheet to make the related posts look better:
.related-posts {
margin-top: 40px;
padding: 20px;
background: #f9f9f9;
border-top: 2px solid #ddd;
}
.related-posts h3 {
font-size: 20px;
margin-bottom: 15px;
}
.related-posts ul {
list-style: disc;
margin: 0;
padding-left: 20px;
}
.related-posts li {
margin-bottom: 8px;
}
Step 3: Optional – Display Thumbnails
If you want to show featured images along with titles, modify the loop inside the code:
while ($related->have_posts()) {
$related->the_post();
echo '<li>';
if (has_post_thumbnail()) {
echo '<a href="' . get_permalink() . '">';
the_post_thumbnail('thumbnail');
echo '</a>';
}
echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
echo '</li>';
}
Step 4: Use a Plugin (Alternative)
If you prefer not to add custom code, there are plugins that can handle related posts automatically:
Summary
- Use
wp_get_post_categories()andWP_Queryto fetch related posts by category. - Exclude the current post with
post__not_in. - Display results as a simple list or with featured images.
- Style the output with CSS for better presentation.
- Alternatively, use a plugin if you want a ready-made solution.
By adding related posts by category, you can keep visitors engaged, reduce bounce rates, and increase time spent on your WordPress site.
🎨 Want to learn more? Visit our WordPress Customization Hub for tips and advanced techniques.