How to: Related Posts with Thumbnails in WordPress without Plugins

Posted on February 5th, 2010 by in Themes | 89 Comments  
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

About

Editorial Staff at WPBeginner mainly Syed and David.

Post comment as twitter logo facebook logo
Sort: Newest | Oldest

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

Ferdy 5 pts

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

tobalseverin 5 pts

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!

MetalCarports 5 pts

Does this work for Pages as well or just Posts?

Thanks.

imranhunzai 6 pts

Absolutely awesome! and yeah it helps.

zioneyemedia 5 pts

I do have a question on this: I'm wrestling on the code to capture posts from child categories versus parent categories. Any advice?

dustinporchia 5 pts

I'm trying to use the related posts by category and I noticed that you said the code has to come before the comments in the main loop. In my code I want the related posts to come after the comments in the loop. When I do this I notice my disqus comment plugin takes longer to load now. Is that because of an error with the comments or is that normal?

dustinporchia 5 pts

Nevermind...I just switched to livefyre as this is more of what I'm looking for in a comment system anyways...thanks!

subzerokh 5 pts

please

could someone help a newbie like me customize this script so it'll display related post in an horizontal way?

from left to right..

instead of currently showing it from up to down, vertically...

zioneyemedia 5 pts

Hey,

How I did it is I replaced the <li> and </li> codes with my own html and css. The <li> codes create lists for each post, and that is usually in a vertical fashion.

------------------

<li><div><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(); ?></a></div> <div> <h3><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3> <?php the_time('M j, Y') ?> </div> </li>

------------------

I replaced the opening <li> with <div class="pleft"> and replaced the closing </li> with </div> as my html tags. Then I write my CSS to fit that specific div class needs on your website. For example, a sample pleft class could look like this:

.pleft {float:left; padding:2px; margin:10px; width:278px; height:190px;}

I use the float: selector on my CSS to move posts horizontally, and the margins and padding to give each post spacing within each other. I added in a specific width and height for additional examples.

Hope this helps.

 zioneyemedia thank you! 

subzerokh 5 pts

hello all!! thanks for this wonderfull script!!

It's the only thing i found doing exactly what i wanted!!!

But it's just showing related post in vertical way (from up to down)

I would like it to be shown from left to right (horizontally)

How to do that please??

wpbeginner 60 pts moderator

subzerokh You would have to edit the styling. It is not that hard. Simply wrap each post in a div. Specify a width for that div and then set a float left property. Adjust the margins and such and you have it.

subzerokh 5 pts

wpbeginner hello

thanks for your quick answer...

but i'm a real novice at all you are saying..

can you please give a litlle exemple?

for making them horizontal as on your own blog?

can get in touch by my mail: khiloc at gmail dot com

ConnectIndia 5 pts

Error Fatal error: Call to undefined function the_post_thumbnail() in /home/connec92/public_html/wp-content/themes/weekly/single.php on line 59 Can some one help. website www.connectindia.co.in

xavpro 5 pts

hey,

great post! maybe you could help me:

i have a auto thumb if none is defined,

if ($thumb_array['thumb'] == '') $thumb_array['thumb'] = 'link to your default thumbnail image';return $thumb_array;

now my question is how to define a thumb for each category, which will be used if none is defined at post.

dehahs 5 pts

works nicely, thanks for sharing!

AdnanAsif 5 pts

Hi

thanks for your great post..

But any change to get posts by categories but not in ul and li and not in thumb..

I mean full posts show in related posts..just like show on home page, with readmore link.

thanks

waiting your reply..

ibadullah25 5 pts

Can I have a CSS For this please

titusmagnet 5 pts

Thanks..im searching for this kinda Code

jaffa 5 pts

This is great, just what I have been looking for. I wonder though, how could I combine the two above and if there are no tags then it displays posts from the same category?

Trying to figure this out but not getting very far yet

Thanks for the code it worked but how do I style it. I'd like it to be 4 stories side by side like yours. It is listed one on top of another on my site and not listed like yours.

That is CSS. We are not using this code to show related stories. Second, i believe what you are talking about is featured stories on our sidebar. We have written another post about that in our site.

is ther a way to dispay the thumbs in related post without using featured images or post thumbs??
i.e to use any image used in the post ...

Yes, you can utilize the fallback techniques shared by other developers which pulls the first image from the post. But we recommend using the WordPress post thumbnails...

Thanks for this article. I was wondering if there is a way to auto-tag posts without having to manually enter them.

No you have to tag each post manually.

Great!
What if I want to display related posts by category without thumbnails?
Thanks

Just remove the thumbnail code from the code above :)

Thank you for posting this tutorial, it helps me a lot.

Hi there...Just wanted to say that I've been building my wordpress website from the ground up and this code works perfectly for me using WP 3.1....All I need to do now is style the CSS and get some thumbnails happening for the posts. Thanks for your help with the code.

thanks, i'm looking this hack for so long and you got it to me!

Hi, is there a way to exclude categories? I have two main categories where all the categories get assigned to. The main categories have sub-categories and I would like to show just related posts from the sub-categories.

Is this possible, by excluding the id's of the main categories?

Thanks for your advice!

BTW...love the code...and it works great!!!

You should be able to use category not in <<

प्रतापसिंह 5 pts

please us how to exclude a cat in related post by cati post here http://wordpress.org/support/topic/exclude-category-from-related-posts?replies=4

I was searching for related post with thumbnails plugins but the code that you paste above, solve my problem.

Just one question, is there a way to only pull tags from the same post type? Maybe using something like 'post_type=videos'?

By the way, got this figured out as well:

Just add it to the array:

$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,
'post_type'=>'videos'
);

Hi,

Thank you for this tutorial. I'm wondering though if there's anyway the related products can be randomized? I've checked different products in the same category and the same related products were shown.

Thanks

Yes use the Query_Post parameter for order and you can randomize it.

phdean 5 pts

Hi,

I too would like to randomize the posts that display for the categories as, otherwise, they'll display the same 2 every time. Can you please give me the code to do this?

Many thanks in advance :)

Nevermind, I got it figured out. Thanks for the post!

what was the issue?

I didn't have any other posts with the same tags, i.e. no related posts. Dummy mistake.

I copied this code and put it in my single.php without changing a thing and nothing gets outputted. Anything wrong with my code? pastebin.com/kg0SkrAg

gcog 5 pts

I've got related tags for sure, but when I add the code I see nothing. Also, when I add your code to restrict to a custom post type, it gives me an error. I did change the post type to my specific post type.

This doesn't bring up a thumbnail -- there isn't even a call for an image int eh code. I don't see how anyone can get this to work.

Tweets about us: