How to add Related Posts with (or without) Thumbnails to your WP Blog

Adding related posts to your blog is a great way to help your readers find other posts on your site that interest them. And if you have ads, increasing the number of pageviews on your blog can turn out to be quite lucrative. I recently had a request from a client to use a certain widget that she had seen on many other blogs that adds a list of recent posts along with a thumbnail image from that post. But after looking at the widget and researching the many other plugins that are available to add this functionality, I decided I wanted to find a way to code it directly into the template.

One reason for this is that the more plugins installed on a blog, the more that can slow down the loading time of that blog. If you can hard-code a function into the template, it’s almost always preferable to using a plugin. Plus many of the plugins or widgets I looked at gave very little control over things like styling or where the list appears in the template or even how they even figured out what was “related”. What if you want them to be related by tag instead of category or vice versa? What if you just want other posts by the same author?

After doing some more googling and modifying some of the code I found I figured out how to do everything I wanted to and more. My client was extremely pleased with the results and was amazed that I’d even been able to implement it without using a plugin or the widget she had originally wanted:

“It IS cool! A zillion people are going to see it now and want it on their WP blogs! Thanks!”

Which leads us to this post. I thought I would share my findings so that you can implement the same feature on your own WordPress blog. Below I will show you how to add related posts by category, tag or author. I will preface this by saying you should probably have some very basic knowledge about how to edit a template in WordPress, but for the most part, you can copy the code directly and paste it into your template. That’s it. For people with more advanced knowledge I’ll point out things that you can edit further and customize to your liking.

 

Where to add the code:

To start, you should figure out where you want your related posts to show up. Generally, you are going to want to include this on your single post page, which is the page that has the full post including comments. In your WP admin, click on Appearance>Editor and look for the template called Single Post or single.php. 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.

There will be two separate pieces of code and two different places you need to find in your template to insert them. The first is the beginning of the WP loop and the second is the spot that you want the related posts to show up.

The beginning of your loop is going to look like either of these:

  1. <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  2. or
  3. <?php if (have_posts()) : ?>

The first code snippet should be inserted directly above this line. It’s very important that it’s above because you want it to be outside of the loop. It can create some very weird behavior otherwise, which I found out in the trial and error of testing all of this.

The other code snippet will be inserted inside the loop in the place where you want the related posts to appear on your page. If you’re not sure where it should go generally you are going to want it at the bottom of the post either after the post ends or after the comment link (assuming that’s at the bottom of your post). Look in your template for something that looks like this and insert the code somewhere underneath. You can always move it around until it appears in the place you want it to.

  1. <?php the_content(); ?>
  2. <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?>

 

Adding Thumbnails:

If you want to display thumbnails, you will have to go one step further and add a thumbnail image custom field to your posts. If you want, you can just start doing this on your most recent post, but you may want to go back through previous posts and add thumbnails to them as well (at least the last 5 posts or however many you want to display). Until you have a bunch of posts with thumbnails assigned, it won’t have too much to choose from when displaying the related post list.

custom-field

Adding a custom field is simple. If you haven’t already, upload your photo in WordPress. If you’ve already uploaded the image you want to use, open the uploader and choose the image you want from the gallery. The WP uploader will have created different sizes for you. By Alignment, choose Left and by Size, choose Thumbnail and click the ‘Insert into Post’ button. Copy the entire code snippet and scroll down the post page to the box that says Custom Fields. Under “Add new custom field” click on the “Enter New” link. Under “Name” type: thumbnail. Paste your image code into the large box under “Value”. Click on the button that says “Add Custom Field”. That’s it. Finish and publish your post like normal.

 

See it in Action:

Below is the code you need to implement these functions on your blog. Copy it into your template and you’ll have a simple unordered list without thumbnails. Read the further customization section for what you need to change to make it display thumbnails and other customizations like changing the number of posts or what order they appear in.

But before you see the code (which I realize may just look like a bunch of gibberish to some people), here are some examples of it in action:

Related by Category, with thumbnails:

Related by Tag: Look at the bottom of this very post (or any of the posts on this blog) to see the related post list using this function.

 

Skip Directly to the section you want:

 

Related Posts by Category

Via DarrenHoyt.com

This code searches other posts in the same category and returns the title of 5 random posts in list form.

Insert this above your loop:

  1. <?php
  2. //Gets category info
  3. global $wp_query;
  4. $cats = get_the_category();
  5. $tempQuery = $wp_query;
  6. $currentId = $post->ID;
  7.  
  8. //related category posts
  9. $catlist = "";
  10. forEach( $cats as $c ) {
  11. if( $catlist != "" ) { $catlist .= ","; }
  12. $catlist .= $c->cat_ID;
  13. }
  14. $newQuery = "posts_per_page=6&orderby=rand&cat=" . $catlist;
  15. query_posts( $newQuery );
  16. $categoryPosts = "";
  17. $count = 0;
  18. if (have_posts()) {
  19. while (have_posts()) {
  20. the_post();
  21. if( $count<5 && $currentId!=$post->ID) {
  22. $count++;
  23. $categoryPosts .= '<li><a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';
  24. }
  25. }
  26. }
  27. $wp_query = $tempQuery;
  28. ?>

Insert this in the spot that you want the list to show up:

  1. <h3>Related Posts</h3>
  2. <ul>
  3. <?php echo $categoryPosts; ?>
  4. </ul>

Further Customization

Change the number of posts that show up:

1. On Line 14 of the first snippet, change the number ‘6’ to the number of posts you want plus one. So if you want 10 posts, put in 11.

2. On Line 21 change the number ‘5’ to the number of posts you want to show.

Change the order of posts that show up:

1. On Line 14 change orderby=rand to any of the following:

  • orderby=author
  • orderby=date
  • orderby=title
  • orderby=modified
  • orderby=ID

Display thumbnails, with post title underneath:

1. Change Line 14 to:

  1. $newQuery = "posts_per_page=6&meta_key=thumbnail&orderby=rand&cat=" . $catlist;

This tells it to only search for posts with a thumbnails. If all your posts have thumbnails, then you can skip this step.

2. Change Line 23 to:

  1. $categoryPosts .= '<li><a href="' . get_permalink() . '">' . get_post_meta( $post->ID, "thumbnail", $single = true ) . '</a><br />
  2. <a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';

This is the formatting. Both the thumbnail and the post title below it link to the post’s permalink.

3. You may also want to style your thumbnails (add a border, spacing between them, etc.). The alignleft class should already be in your stylesheet if you have any kind of standard WP theme, but if you don’t see it listed, add this to the end of style.css for some basic styling:

  1. img.alignleft { float: left; }
  2. img.size-thumbnail { padding: 10px; }

 

Related Posts by Tag

I combined code from DarrenHoyt.com and Techie Blues for this function.

This code searches other posts with the same tags and returns the title of 5 random posts in list form.

Insert this above your loop:

  1. <?php
  2. global $wp_query;
  3. $tags = wp_get_post_tags($post->ID);
  4. $tempQuery = $wp_query;
  5.  
  6. if ($tags) {
  7. $tag_ids = array();
  8. foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
  9.  
  10. $newQuery=array(
  11. 'tag__in' => $tag_ids,
  12. 'post__not_in' => array($post->ID),
  13. 'showposts'=>5, // Number of related posts that will be shown.
  14. 'orderby'=>rand,
  15. 'caller_get_posts'=>1
  16. );
  17. query_posts( $newQuery );
  18. $tagPosts = "";
  19. if (have_posts()) {
  20. while (have_posts()) {
  21. the_post();
  22. $tagPosts .= '<li><a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';
  23. }
  24. }
  25. }
  26. $wp_query = $tempQuery;
  27. ?>

Insert this in the spot that you want the list to show up:

  1. <h3>Related Posts</h3>
  2. <ul>
  3. <?php echo $tagPosts; ?>
  4. </ul>

Further Customization

Change the number of posts that show up:

1. On Line 13 from the first snippet, change the number ‘5’ to the number of posts you want to show.

Change the order of posts that show up:

1. On Line 14 change ‘orderby’=>rand, to any of the following:

  • ‘orderby’=>author,
  • ‘orderby’=>date,
  • ‘orderby’=>title,
  • ‘orderby’=>modified,
  • ‘orderby’=>ID,

Display thumbnails, with post title underneath:

1. Under Line 13 add:

  1. 'meta_key'=>thumbnail,

This tells it to only search for posts with a thumbnails. If all your posts have thumbnails, then you can skip this step.

2. Change Line 22 to:

  1. $tagPosts .= '<li><a href="' . get_permalink() . '">' . get_post_meta( $post->ID, "thumbnail", $single = true ) . '</a><br />
  2. <a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';

This is the formatting. Both the thumbnail and the post title below it link to the post’s permalink.

3. You may also want to style your thumbnails (add a border, spacing between them, etc.). The alignleft class should already be in your stylesheet if you have any kind of standard WP theme, but if you don’t see it listed, add this to the end of style.css for some basic styling:

  1. img.alignleft { float: left; }
  2. img.size-thumbnail { padding: 10px; }

 

Related Posts by Author

Via DarrenHoyt.com

This code searches other posts by the same author and returns the title of 5 random posts in list form.

Insert this above your loop:

  1. <?php
  2. //Gets author info
  3. global $wp_query;
  4. $postAuthor = $wp_query->post->post_author;
  5. $tempQuery = $wp_query;
  6. $currentId = $post->ID;
  7.  
  8. //related author posts
  9. $newQuery = "posts_per_page=6&orderby=rand&author=" . $authorPosts;
  10. query_posts( $newQuery );
  11. $authorPosts = "";
  12. $count = 0;
  13. if (have_posts()) {
  14. while (have_posts()) {
  15. $count++;
  16. the_post();
  17. if( $count<5 && $currentId!=$post->ID) {
  18. $count++;
  19. $authorPosts .= '<li><a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';
  20. }
  21. }
  22. }
  23. $wp_query = $tempQuery;
  24. ?>

Insert this in the spot that you want the list to show up:

  1. <h3>More Posts by this Author</h3>
  2. <ul>
  3. <?php echo $authorPosts; ?>
  4. </ul>

Further Customization

Change the number of posts that show up:

1. On Line 9 of the first snippet, change the number ‘6’ to the number of posts you want plus one. So if you want 10 posts, put in 11.

2. On Line 17 change the number ‘5’ to the number of posts you want to show.

Change the order of posts that show up:

1. On Line 9 change to orderby=rand to any of the following:

  • orderby=date
  • orderby=title
  • orderby=modified
  • orderby=ID

Display thumbnails, with post title underneath:

1. Change Line 9 to:

  1. $newQuery = "posts_per_page=5&meta_key=thumbnail&orderby=rand&author=" . $authorPosts;

This tells it to only search for posts with a thumbnails. If all your posts have thumbnails, then you can skip this step.

2. Change Line 19 to:

  1. $authorPosts .= '<li><a href="' . get_permalink() . '">' . get_post_meta( $post->ID, "thumbnail", $single = true ) . '</a><br />
  2. <a href="' . get_permalink() . '">' . the_title( "", "", false ) . '</a></li>';

This is the formatting. Both the thumbnail and the post title below it link to the post’s permalink.

3. You may also want to style your thumbnails (add a border, spacing between them, etc.). The alignleft class should already be in your stylesheet if you have any kind of standard WP theme, but if you don’t see it listed, add this to the end of style.css for some basic styling:

img.alignleft { float: left; }
  1. img.size-thumbnail { padding: 10px; }

Comments

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

    • 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="http://path/to/your/thumbnail.jpg" class="alignleft thumbnail" alt="Image Name" / >

  2. 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. hi,

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

    thx for help!!
    mw

    • 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. 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. 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.

Leave a Reply