Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to: Related Posts with Thumbnails in WordPress without Plugins

Last updated on by
Follow WPBeginner on YouTube
How to: Related Posts with Thumbnails in WordPress without Plugins

Related posts can be easily displayed with plugins, but did you ever wonder how you could display related posts with a Thumbnail without using a Plugin? In this article, we will share two different algorithm which you can use to generate related posts with thumbnails and avoid using any plugin.

Note: We will utilize the built-in WordPress Post Thumbnail Function. So it is best if you implement this.

Related Posts by Tags

WordPress has this amazing taxonomy known as “Post Tags” which you can use. You can tag each of your posts with multiple keywords. This algorithm would find other posts with any one of the tag that the current post has and will list them.

<?php $orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>5, // Number of related posts that will be shown.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {

echo '<div id="relatedposts"><h3>Related Posts</h3><ul>';

while( $my_query->have_posts() ) {
$my_query->the_post(); ?>

<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_time('M j, Y') ?>
</div>
</li>
<? }
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>

The above code is looking at the current post ID and all tags which are associated with it and it uses the wp_query function to look for all other posts that matches any original tag and display them. You can style the post anyway you want them.

Advantage: Most codes on the web cannot be used within the main post loop. Because the related posts are placed right after the main post and above the comments, this code is very helpful. We are saving the current post ID of the main loop and then recalling it at the end of our related posts code. Usually when you don’t do it this way, the two post ID codes gets mixed up and then the comments start acting weird which can break the comments, other plugins related to comments such as numbering system etc. So this code is good and it works.

Usage: Place this code anywhere you like in your single.php and it will work. But most of the time it is placed right above the comments in the main loop.

Related Posts by Category

This algorithm would find other posts within the same category as the current post, and it will list them as related posts. The advantage of this technique is that you will never have a blank spot for your related posts section.

<?php $orig_post = $post;
global $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;

$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=> 2, // Number of related posts that will be shown.
'caller_get_posts'=>1
);

$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo '<div id="related_posts"><h3>Related Posts</h3><ul>';
while( $my_query->have_posts() ) {
$my_query->the_post();?>

<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div>
<div class="relatedcontent">
<h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_time('M j, Y') ?>
</div>
</li>
<?
}
echo '</ul></div>';
}
}
$post = $orig_post;
wp_reset_query(); ?>

This technique utilizes the same functions as the one above except we are just using the different criteria.

If you are creating a new project, or working on a client’s site, this could be very helpful.

Example

Add Related Posts with a Thumbnail in WordPress without using Plugins

Additional Sources:

Creating a Mini Plugin to Show Related Posts via Functions.php

Query Function and Template Tags for WordPress


Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
  • Jonas

    My thumbnails are too big, help. How can you limit the related posts thumbnails?

  • Jonathan

    Is there a way to choose a single category (let’s call it Brands) and then have it display related posts only affiliated with the child categories under Brands? So, the hierarchy for the cats would be Brands > JCPenny. I want to only show related posts for JCPenny. But, that child category could be different per post. So if a post uses a different child category it’ll show related posts for that child cat. Can this code be modified to handle that somehow?

    • Jonathan

      OH! I think I’ve got it. I just added ‘parent’ => ‘the cat id number’, to the args and I think that did it.

    • Jonathan

      wait… no, that didn’t work :(

  • Miro

    Hi, thanks for the code, but instead of grabbing the featured image as a thumb, can i grab instead the first image in my posts? Thanks

    • http://www.wpbeginner.com/ WPBeginner Support

      This sounds like a nice post idea, we will cover it soon in a new article. Thanks for the feedback.

      • Miro

        It would be great if you guys would make a post on it. Thank you very much and will be waiting. Hope that you can kindly post here a notification once you made the post so we know.

  • Caleb

    Great post thanks! I run a website that uses WP more as a CMS with a large number of pages rather than posts. Can I do this with as related pages instead, so that it’s grabbing related pages and not posts? If so how do I go about doing this.

    Thanks for the help :)

  • Muhammad Hadi Qureshi

    Really thanks for this helping post

  • Phil Simon

    This. Is. Awesome. WPEngine understandably doesn’t allow for related posts plugins, save for a few exceptions. I tried a few and really didn’t like them. I threw this code into single.php and voila! Thank you.

  • Lucas Bishop

    This is good, but i wanna do it with title of post rather then tags or category. Any suggestions for it, syed!!

  • Alexandros

    Hi friends little problem it appears to me: “Parse error: syntax error, unexpected ‘endwhile’ (T_ENDWHILE) in C: \ xampp \ htdocs \ z1 \ wp-content \ themes \ mytheme \ single.php on line 65″ find
    But what ..? Thanks

    • http://www.wpbeginner.com/ WPBeginner Support

      Try pasting the code below the endwhile; in your single.php file.

  • Britt

    Love this piece of code, use it on the regular! One question: Is there a way to exclude some tags in the code?

  • Rakesh

    Take a look at the category related posts code. It wont work unless you add some php , the three letters before getting started with echo. Add php and it will not be ignored. In either case, it is ignored and wordpress cries every time with an error note. Thanks for the code by the way and it made my work a lot easier. Thanks a ton for that and do adjust it ,

  • Dennis

    Also, I have one more question,

    What if I wanted to display a certain post containing a certain tag to all posts, how would I do this?

  • Dennis

    Hi, this is so awesome! Now I can just get rid of my related post plugin, so thanks A LOT for that!

    One question I have is, how can I display the related post in 2 column?

    Once again, this has been such a BIG help for me!

  • Christina

    Hi!! Thanks for your helpful information for those, like myself, who have no idea of any coding, but still want to have a blog!! I have just incorporated your ‘relate posts by tags” code to my single post file. It works except for the pfotos. They dont show at all and the titles of my related posts are shown the one under the other, like a list. What have I done wrong?? Thanks in advance for your answer!!

    • http://www.wpbeginner.com/ WPBeginner Support

      It seems like you are not using post thumbnails or featured images with your posts in WordPress. Also you may need to tweak the CSS a little bit/

  • TheFran

    Hi,

    This code is amazing! Thank you so much. Is there a way I can make the code show related posts from ANOTHER SITE? So it searches the posts from another site that I show below the post as a related post on my site?

    Thanks!

    • http://www.wpbeginner.com Editorial Staff

      Not using this snippet. You would have to create something more complex for that.

  • Carlos

    Hi,
    I’m using a theme that works with custom posts. I wonder if I try your code, which part should I edit to display just those custom posts instead of the regular posts.

    Thanks

  • Miz.Chellie

    Hello – yours is the first tutorial that I found that works but I would like the list vertical. Can you give an example of the CSS for that?

  • Livius

    Hey,

    I cannot, find the single.php where I have to insert this code.

    The problem is that I am using Balance Theme + Genesis. So in the genesis, I can find the Single.php, but it says to “Not Edit Under Any Circumstances”, and I have actually pasted the code in there, but it made my site to stop opening pages at all.
    And in the Child Balance Theme, there is no Single.php ….

    Any suggestions?

    • http://www.wpbeginner.com Editorial Staff

      Yes, don’t edit the framework file. You would have to familiarize yourself with Genesis hooks and filters. Then add the code in one of the loop hooks for single page using your functions.php file. Unfortunately, due to the amount of frameworks out there, we can’t possibly cover our tips for all frameworks.

    • Mark

      Use Genesis Hooks then put the code in there.

  • peter

    Hello is there any way to change the thumbnail size? i get only one related post and its thumbnail is huge

  • Dean

    Hi! this is very useful coding. Is it possible to use this for making a custom page that will show all the posts, like a sitemap but with thumbnails? Something like this:

    Category 1
    —– related posts code (all posts from that category) ——

    Category 2
    —– related posts code (all posts from that category) ——

    etc. It would make a great showcase for categories with few posts. Thank you for reading and help!

    • Dean

      hey, found something here.. I will try that :)

  • http://www.facebook.com/profile.php?id=549944278 Nuno Marques

    Hey,

    very handy your “Related Posts by Category”.

    Sometimes I believe it’s better to have add a raw code rather than use a plugin doesn’t is so expansible…

    Thank you!

  • Silverbadger

    Is it possible to display the posts horizontal instead of vertical?

    Thanks :)

    • http://www.wpbeginner.com Editorial Staff

      Yes, you can simply adjust the CSS.

  • Paul

    Thank you thank you thank you!! A simple copy paste bit of code that just gets on with it and works – does exactly what it says. This is exactly what I was looking for :)

  • http://www.wpbeginner.com Editorial Staff

    Yes, you can use post thumbnails by itself. Not sure why you would want the related feature…

  • http://www.softstech.com/ Raheek

    Thanks for the helpful article. I now just added elated posts by using this code.

  • http://imarketingbiz.net/ Ferdy

    What if there are no related posts. can it be coded such that it falls back to category related.

  • tobalseverin

    hi!

    i need some help…

    How i can filter.. the category, but if i have parent and child categories and only i show the child post. ex:

    – product (all product, this is the parent) (id 104)

    – KindOfProducts (subcategory, this is the child) (id 109)

    – KindOfProductsTwo (subcategory, this is the child) (id 110)

    in products have all post but just need show related from the child: KindOfProducts.

    i try whit this:

    $args = array(

    ‘category__in’ => $category_ids,

    ‘category__not_in’ => 104,

    ‘post__not_in’ => array($post->ID),

    ‘orderby’=> ‘rand’,

    ‘showposts’ => 100,

    ‘ignore_sticky_posts’ => 1

    );

    but dont showme nothing…

    and i try whit this other one:

    $args = array(

    ‘category__in’ => $category_ids,

    ‘child_of’ => 104,

    ‘post__not_in’ => array($post->ID),

    ‘orderby’=> ‘rand’,

    ‘showposts’ => 100,

    ‘ignore_sticky_posts’ => 1

    );

    and nothing

    help? tnks!