Wordpress Snippets

Display Related Posts Without Plugin

When visitors finish reading one of your posts, it is important to provide a clear “what next?” option. In the absence of cues to keep interacting with your site, visitors are more likely to leave your website. Displaying a list of related posts just below individual posts is a great way to keep readers engaged on your blog. This will improve your visitor experience, increase page views and decrease your bounce rate.

A number of plugins exist that generate “related posts” on your site. Yet Another Related Posts Plugin is one of the most popular plugins for generating and displaying related posts in WordPress. The majority of these plugins rely on post tags as an indication of relevance. So we are also going to try to achieve just that but without any plugin. We will display related posts based on tags of current post. Although I would recommend you to use a plugin if you are looking for a fully featured solution for displaying related posts in WordPress.

You can use this code snippet in your theme files to display related posts anywhere you want. In this following example we are displaying 5 related posts. You can change this number with a number of posts you want to show.

<?php
// display 5 related posts by first tag of current post
$tags = wp_get_post_tags( $post->ID );
if ( $tags ) {
    $first_tag = $tags[0]->term_id;
    $args = array(
        'tag__in' => array( $first_tag ),
        'post__not_in' => array( $post->ID ),
        'posts_per_page' => 5,
        'ignore_sticky_posts' => 1
    );
    $related_posts = new WP_Query( $args );
    // the loop
    if ( $related_posts->have_posts() ) :
        while ( $related_posts->have_posts() ) : $related_posts->the_post();
            get_template_part( 'content', get_post_format() );
        endwhile;
    else :
        get_template_part( 'content', 'none' );
    endif;
    wp_reset_postdata();
}
?>

Hire Us. Or just say Hi!
Need a job? Apply to get one.