How to add Related Posts to your WordPress blog

Date January 28, 2019 ▪ Folder ,

Adding related posts to your WordPress blog is a great way to help your readers find more posts on your site that interest them. And in business terms that leads to more engagement and pageviews for your blog. Plus, adding links to other posts on your site is a great SEO practice.

There are several plugins that can add this feature for you, but the more plugins you have installed the slower your blog will be. So I always try to avoid unnecessary plugins if I can. Also, many of the plugin options are very basic and give you very little control over things like styling or where the list appears in your theme or even how they even figured out what was “related”.

Below I will show you how to add related posts by category, tag, or any other custom taxonomy. I’ll preface this by saying you should probably have some very basic knowledge about how to edit a theme in WordPress, but for the most part, you can copy the code directly and paste it into your templates. That’s it. For people that want to go further I’ll point out things that you can customize to your liking.

How to Add Related Posts to your WordPress blog

Before you Start:

If you are using a theme that you bought or downloaded for free, you should always create a child theme first so that you can upgrade your theme later without losing these customization.

The thumbnails are pulled from the featured image for each of your posts, so you may need to go back and set a featured image on your posts if you haven’t already. But don’t worry, if you don’t have any featured images set, this will still work, it just shows a text link instead of an image.

Step 1

First, you need to edit your functions.php file and add this code:

/**
 * Related posts
 * 
 * @global object $post
 * @param array $args
 * @return
 */
function swanky_related_posts($args = array()) {
    global $post;
 
    // default args
    $args = wp_parse_args($args, array(
        'post_id' => !empty($post) ? $post->ID : '',
        'taxonomy' => 'category',
        'limit' => 4,
        'post_type' => !empty($post) ? $post->post_type : 'post',
        'orderby' => 'date',
        'order' => 'DESC'
    ));
 
    // 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']
    ));
 
    include( locate_template('related-posts-template.php', false, false) );
 
    wp_reset_postdata();
}

Step 2

Next, create a new file called related-posts-template.php and copy this into it:

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

Upload your updated related-posts-template.php file to your child theme folder.

Step 3

Now you need to decide where you’d like to add your related posts. You are always going to want to add it to your single post template, which is the page that has the full post including comments. But you may also want it to show up on your main page (index.php) and your archives (archive.php). If you do want this to show up on all three templates, generally you can just copy and paste the same code in the same spot on all of them, but some themes may have the archives or index page formatted differently. When in doubt just put it on the single post template and that’s probably enough.

You’ll probably want to insert your related posts at the end of post, before the comments start so look for this template tag:

<?php the_content(); ?>

Insert this directly under it:

<?php swanky_related_posts(); ?>

Customizing the Look

You may also want to style your thumbnails (add a border, spacing between them, etc.). Add this to your stylesheet (style.css) to get started:

ul.related-posts-list { 
	list-style-type: none; 
	text-align: center; 
	margin: 0 auto; 
	padding: 0; }
 
ul.related-posts-list li { 
	list-style-type: none; 
	display: inline-block; 
	margin: 0; 
	padding: 10px; 
	vertical-align: top; }
 
ul.related-posts-list li img.size-thumbnail { border: 1px solid #666; }
 
.clearfix { clear: both; }

Further Customizations

Show related posts using tags instead of categories:

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

Change how many posts show up:

The default is set to show 4 posts, but you can show as many as you want.

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

Change the order of the posts:

By default, the related posts will show up in descending order (newer posts first), by date but there are many parameters to choose from.

Random order, older posts first:

<?php swanky_related_posts(array( 'orderby' => 'rand', 'order' => 'ASC' ));?>

Show posts with the most comments first:

<?php swanky_related_posts(array( 'orderby' => 'comment_count' ));?>

This post was originally written in 2009 but has been completely updated in 2019 to work with the newest version of PHP.



Comments

  1. razv4n says:

    Pleaze help me , i did everithing corect but it doesn’t show my imeges , unly theyr URL . See my website :www.desprefilme.com

    • Emily says:

      It sounds like you just put the image URL in the custom field instead of the full image code. Check your custom field value and make sure it looks something like this:

      < img src="https://path/to/your/thumbnail.jpg" class="alignleft thumbnail" alt="Image Name" / >

  2. jesse says:

    I have custom posts (using custom field templates) that are used for music releases in cd format. I wanted each post in the cd_release category to show other cd releases on the single.php page and this works perfectly. I tried some plugins but they seemed to be more work finding any documentation. Thanks for sharing this.

  3. mw says:

    hi,

    nice code! is there a way to exclude some categories from the list?

    thx for help!!
    mw

    • Emily says:

      To exclude certain categories from the related posts by category you would insert the category IDs you want excluded before it calls the post’s category.

      So line 14 would look like this:

      $newQuery = "posts_per_page=6&orderby=rand&cat=-3,-6,-8," . $catlist;

      The number is the ID of that category and you can list as many as you want. The minus in front means you want it excluded.

      To exclude certain categories from the related posts by authors you would insert “cat=-3,-6,-8” into line 9.

      It would look like this:

      $newQuery = "posts_per_page=6&cat=-3,-6,-8&orderby=rand&author=" . $authorPosts;

      To exclude categories from the related post by tag, you would insert this line AFTER line 13:

      'cat'=>-3,-6,-8,

      For all of these, if you instead wanted it to show ONLY certain categories then it would be the same, but list the category IDs without a minus in front. Then it would find posts ONLY in those categories.

  4. mw says:

    Perfect!!

    is there an way to tell the code just to show the category i am already reading?
    example: a post ist listed in category 1,2,3. when i am reading the post in cat 1, i get the recent posts of cat 1 in the buttom of the page. if i am reading this post in cat 2, i get the posts of cat 2 …

    thx for help … and sorry for my bad english :-))

  5. Eddie Gear says:

    Hi there,

    Thanks for writing this post, I found it very useful when all the WP plug-in available did not do the job. As a designer and developer of WP themes. This helped me take things to the next level on my blog.

Add A Comment