For most publisher websites, it’s often a great idea to show your readers other posts that are related to the article they’re reading. A great way to do this is to add a “Related Posts” section at the bottom of the article that lists a few more related topics.
Some WordPress themes might not have this feature so it’s up to the developer to create this. Here’s the sample code of a “Related Posts” WordPress loop that you can copy. It’s usually common to place this after the post’s content.
<div id="related-posts" >
<h2>You might also like</h2>
<div class="inner-related-posts">
<?php
// args to get posts from the related category
$feed_args = array(
'category__in' => wp_get_post_categories( get_queried_object_id() ),
'posts_per_page' => 7,
'orderby' => 'DESC',
'post__not_in' => array( get_queried_object_id() )
);
$feed_query = new WP_Query( $feed_args );
if ( $feed_query->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $feed_query->have_posts() ) : $feed_query->the_post();
// Get the primary category name
$feed_categories = get_the_category();
$feed_cat_name = $feed_categories[0]->cat_name;
?>
<div class="card">
<a class="card-img" style="background-image: url(<?php echo get_the_post_thumbnail_url();?>);" href="<?php the_permalink(); ?>"></a>
<div class="card-text">
<div class="card-category"><?php echo $feed_cat_name;?></div>
<h3 class="card-post-title"><a href="<?php the_permalink(); ?>"><?php echo get_the_title();?></a></h3>
<div class="card-post-author">By <?php the_author();?></div>
</div>
</div>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
<?php endif; ?>
</div>
</div>
To add some style, you will need to include some CSS’s:
.card {
padding: 10px 0;
border-top: 1px solid #eee;
}
.card-img {
display: inline-block;
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
width: 38%;
padding-top: 20%;
}
.card-text {
display: inline-block;
width: 55%;
vertical-align: top;
padding: 0 10px;
}
.card-category {
font-size: 14px;
text-transform: uppercase;
}
.card-post-title {
margin-top: 2px;
margin-bottom: 5px;
}
.card-post-author {
font-size: 14px;
color: #a9a9a9;
}
The end result would look like this. The sample loop calls more posts from the same category and lists them with thumbnail, title, and author name.
Why is it good to have a “Related Posts” section?
It is a great idea to have a “Related Posts” section to entice your readers to stay on your website. The longer they stay in your website, the better your Bounce Rate and Average Time on Page scores will be in Google Analytics. Both are great indicators for search engines to feature your website to searchers. Thus, it can help with your website’s SEO ranking and trust rating.