search ]

How to add WordPress Related Posts Without a Plugin

Displaying Related Posts on your blog can enhance user engagement with your site’s content, keep visitors on your site for longer periods, and contribute to your site SEO  by improving the user experience.

And as due to security, performance, and similar reasons, we try to use fewer plugins. Even in this case, it would be advisable to add or display Related Posts (also known as Popular Posts) on your site without a plugin.

But before we see how to do that, let’s briefly explain the advantages of adding such component to your blog…


Why Add Related Posts at the End of an Article?

Those relevant articles, as their name implies, contain posts that are relevant to the topic of the article the reader is currently reading.

This is a highly functional feature commonly found on websites in general and WordPress sites in particular. It can benefit your WordPress site in several ways. Here are some of them:

  • They enhance the user experience – Displaying relevant articles is a non-intrusive and very convenient way for your users to discover articles that are relevant to their interests.
  • They help you rank higher – A crucial part of On-Page SEO and optimization for Google and search engines is the correct Internal Linking strategy. Relevant articles are a part of this strategy, automatically helping you build internal links and assisting Google and various search engines in understanding your site’s structure.
  • They reduce bounce rate – We all try to reduce bounce rates on our sites. Visitors interested in specific content are more likely to click on those links, thereby decreasing the bounce rate and keeping them on your site for a longer time.
  • They provide access to old content – If you frequently add content to your blog, older content quickly gets buried in the later pages that visitors often don’t reach. Adding relevant articles at the end of each post is an excellent way to showcase that hidden content to your visitors.

While these relevant posts are displayed automatically, we’ll ensure that posts specifically tailored to the current post’s content are always shown to the reader.

Determining which posts are relevant to the current post can be done based on categories, tags, or taxonomy in the function outlined below.

Adding Related Posts in WordPress Template

You can add related articles to your template in a few simple steps.

Step One is to add the following code to the functions.php file. If you’re using a child theme, add the code to the functions.php file of your child theme.

<?php

// ********* BEGIN HERE *********

function sv_related_posts($args = array()) {

    global $post;

    // default args
    $args = wp_parse_args($args, array(
        'post_id' => !empty($post) ? $post->ID : '',
        'taxonomy' => 'category',
        'limit' => 3,
        'post_type' => !empty($post) ? $post->post_type : 'post',
        'orderby' => 'rand'
    ));

    // check taxonomy
    if (!taxonomy_exists($args['taxonomy'])) {
        return;
    }

    // post taxonomies
    $taxonomies = wp_get_post_terms($args['post_id'], $args['taxonomy'], array('fields' => 'ids'));

    if (empty($taxonomies)) {
        return;
    }

    // query
    $related_posts = get_posts(array(
        'post__not_in' => (array)$args['post_id'],
        'post_type' => $args['post_type'],
        'tax_query' => array(
            array(
                'taxonomy' => $args['taxonomy'],
                'field' => 'term_id',
                'terms' => $taxonomies
            ),
        ),
        'posts_per_page' => $args['limit'],
        'orderby' => $args['orderby'],
        'order' => $args['order']
    ));

    if (!empty($related_posts)) { ?>
        <div class="related-posts">
            <h3 class="widget-title"><?php _e('Related articles', 'textdomain'); ?></h3>

            <ul class="related-posts-list">
                <?php
                foreach ($related_posts as $post) {
                    setup_postdata($post);
                    ?>
                    <li>
                        <a class="title" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                            <?php if (has_post_thumbnail()) { ?>
                                <div class="thumb">
                                    <?php echo get_the_post_thumbnail(null, 'medium', array('alt' => the_title_attribute(array('echo' => false)))); ?>
                                </div>
                            <?php } ?>
                            <h4><?php the_title(); ?></h4>
                        </a>
                    </li>
                <?php } ?>
            </ul>
            <div class="clearfix"></div>
        </div>
        <?php
    }

    wp_reset_postdata();
}

Pay attention that if you are interested in using the translation files of the template – you should replace textdomain in line number 48 with textdomain of your template. Otherwise, simply change the text “Related Posts” to whatever you want.

Step Two is to call the function sv_related_posts() wherever you want in your template, usually you’ll want to add it in the single.php file after calling the_content().

The arguments you can use

The function itself is quite versatile and can be used with several arguments to display relevant content according to the requirements of your WordPress site – or more accurately, your blog.

You can determine the number of posts to be displayed, their order, the taxonomy by which the content will be displayed, and more.

In essence, you can use any argument for the get_posts() function upon which the code we showed above is based, with one minor change – to limit the number of displayed posts, use the limit argument, which is translated as posts_per_page argument in WordPress’s loop.

That’s basically it. Now, let’s provide some examples of how to use the function we created…

Related Posts – Examples of using the function we created

1. Displaying three Related Posts:

<?php sv_related_posts(); ?>

The default arguments of the function is to work by categories, where only 3 posts will be displayed.

If you want to change the number of displayed posts, simply use the limit argument, as in the following example:

<?php
sv_related_posts(array(
    'limit' => 6
));
?>

2. Displaying Related Posts based on tags (which are a taxonomy for everything):

<?php 
sv_related_posts(array(
   'taxonomy' => 'post_tag',
));
?>

3. Displaying six Related Posts by categories, ordered by the number of comments:

<?php 
wcr_related_posts(array(
   'limit' => 6,
   'orderby' => 'comment_count',
   'order' => 'ASC'
));
?>

Take a look at additional sorting options in the WordPress Codex.

4. Displaying articles for a custom content type:

As mentioned, you can use this function for Custom Post Types as well. However, to do so, you need to define and use taxonomy for that content type, since without that taxonomy, we cannot link the existing posts in that content type.

Nevertheless, here is an example that displays relevant articles from the teams taxonomy:

<?php
sv_related_posts(array(
    'taxonomy' => 'teams'
));
?>

Since in 99% of cases, when we are in a specific post, the relevant articles will be of the same content type, there is no need to specify the content type in the arguments. The function automatically identifies the content type we are in.

Conclusion

As we have seen, adding relevant articles to your blog is an efficient way to enhance the user experience. By displaying content that is relevant to the content the visitor needs, we increase the likelihood that the visitor will click on that article, thus continuing to browse your blog.

This action, as we mentioned, helps reduce bounce rates, improve visitor retention on your site, and even helps create a loyal following for your blog. If you have any questions or find any mistakes in the code, I would appreciate it if you share them in the comments.

Roee Yossef
Roee Yossef

I develop custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...