Tutorial Details
- Program: WordPress
- Version (if applicable): 3.0 +
- Difficulty: Intermediate
- Estimated Completion Time: 30-45 mins.
Displaying related posts is a great way to keep readers on your blog and this tutorial will show you how to achieve just this! There are definitely many related posts plugins out there that would be great to use, however I couldn’t find any plugins that fit exactly what I needed. So after a lot of reading and researching, here’s what I ended up with that’s helped me on a ton of my client’s projects including my own. Here I will show you how to program a custom WordPress loop that will display your related posts with thumbnails.
Step 1 Edit your functions.php file
First thing’s first, open up your functions.php file and add this little bit of code:
add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 196, 110, true );
Be sure to replace the 196 and 110 with your own dimensions. Save it and upload the file. After you upload it, in your post sidebar you’ll see a new option titled “featured image”. You can upload any image you want to use here and this will be the image that will display in the related posts section. And make sure you tag all of your posts with at least one keyword. That way when you use this code, you can actually display other posts with any specific tag that the current post has.
Step 2 Edit your single.php file
Now, open your single.php file and add this block of code anywhere you want the related posts section to show up.
<?php
$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),
'showposts'=>4, // 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();
?>
<?php
if ( has_post_thumbnail() ) { ?>
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail(); ?><?php the_title(); ?></a></div></li>
<?php } else { ?>
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><img src="<?php echo get_post_meta($post->ID, 'Image',true) ?>" width="196" height="110" alt="<?php the_title_attribute(); ?>" /><?php the_title(); ?></a></div></li>
<?php }
?>
<?php
}
echo '</ul>';
}
}
$post = $backup;
wp_reset_query();
?>
Just change the ‘showposts’=>4 to however many posts you want to show.
Optional Default Image
If you don’t tend to use images in your posts too much but still want the ability to use the related posts with a thumbnail, replace this line above:
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><img src="<?php echo get_post_meta($post->ID, 'Image',true) ?>" width="196" height="110" alt="<?php the_title_attribute(); ?>" /><?php the_title(); ?></a></div></li>
with this:
<li><div class="relatedthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><img src="<?php bloginfo('template_url'); ?>/images/post-thumb.jpg" width="196" height="110" alt="<?php the_title_attribute(); ?>" /><?php the_title(); ?></a></div></li>
This will pull a default image from your theme folder just in case you don’t have an image assigned to any post.
Step 3 Make it Look Good with CSS!
#relatedposts h3 { font-size: 24px; margin: 10px 0px 20px 0px; font-weight: normal; }
#relatedposts ul { list-style: none; }
#relatedposts ul li { float: left; margin-right: 15px; width: 206px; }
#relatedposts img { border: 1px solid #DDD; background: #F8F8F8; padding: 5px; margin-bottom: 5px; }
#relatedposts a:hover { color: #51B1D3; }
Above is just an example of what you can do with CSS and your related posts code. And that’s it! You have a fully functional related posts section on your WordPress site.
Here’s a Screenshot of the Finished Product



Will any of this code work with all the lines commented out? Most of the code you have is commented out by double slashes (//).
I have a feeling that’s on purpose, so you can’t copy n’ paste.
doubt that, seems kinda silly to be doing that in a tutorial
Al
True – it was just our code highlighter acting up – it’s been removed now
Is it better to get related posts by tags or by category?
I think it depends on your application.
I mean in terms of click-through rate is it preferred to be related tags or category?
I’d rather code this function via a shortcode, seems a proper way to add this feature wherever you want, including single page template, so you could pass arguments to change the number of posts to display and so on.
But if you had it as a shortcode then you would have to remember to put it in after each post. Why not just let a plugin take care of it.
No, you could paste the shortcode in the single.php file.
Say you have many custom page and want to use this related post to only SOME of them, so using the shortcode will be really flexible.
How do you code it as a shortcode? I’d rather not use this as a plugin. If it can be hard-coded into my theme then I’d be a happy woman.
very nice, great post.
thanks,
saludos,
Felipe…..
thank you very much!
Hey everyone. Thanks for reading my tutorial. I have to look into those double slashes, they’re not supposed to be there. I will get that addressed asap.
And to Paul, it’s really about what you’re trying to do. If you only have 1 category and a few tags, then it makes more sense to display by tags. If you have multiple categories and want to show similar posts from the same category, then that makes sense. I can also include the code to display by category instead of tags if you need it.
At Guillaume, definitely a good idea. This is just the basic code to display related posts. Tweaking it to your liking is highly encouraged!
Is there any how to have related post thumbnails without adding featured picture?
F.e. can related post thumbnail be shown from an embedded picture inserted into post?
yeah actually. ok in the functions you put this instead:
function catch_that_image() {
global $post, $posts;
$first_img = ”;
$new_img_tag = “”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘/<img.+src=[\'"]([^\'"]+)[\'"].*>/i’, $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image with 0 width
$new_img_tag = “<img src=’/images/noimage.jpg’ width=’0px’ class=’alignright’ />”;
}
else{
$new_img_tag = “<img src=’” . $first_img . “‘ width=’196px’ class=’alignright’ />”;
}
return $new_img_tag;
}
and then instead of the 2nd option
<img src=”<?php bloginfo(‘template_url’); ?>/images/arrow.png” width=”196″ height=”110″ alt=”<?php the_title_attribute(); ?>” />
you put this:
<?php echo catch_that_image() ?>
how i can add at blog home ?? or somethink like ads under navigation on this site ? please help me ..
I’m not sure what you mean. There’s really no point in showing related posts on the home page since there’s nothing to relate to. Do you mean just showing posts on the home page itself?
I apologize for the faulty code above, totally my fault (forgot to replace the ) here is the proper code below for the single.php and the optional default image:
First the single.php code:
<?php
$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),
‘showposts’=>4, // 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();
?>
<?php
if ( has_post_thumbnail() ) { ?>
<li><div class=”relatedthumb”><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title_attribute(); ?>”><?php the_post_thumbnail(); ?><?php the_title(); ?></a></div></li>
<?php } else { ?>
<li><div class=”relatedthumb”><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title_attribute(); ?>”><img src=”<?php echo get_post_meta($post->ID, ‘Image’,true) ?>” width=”196″ height=”110″ alt=”<?php the_title_attribute(); ?>” /><?php the_title(); ?></a></div></li>
<?php }
?>
<?php
}
echo ‘</ul>’;
}
}
$post = $backup;
wp_reset_query();
?>
and now the optional default image:
<li><div class=”relatedthumb”><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title_attribute(); ?>”><img src=”<?php bloginfo(‘template_url’); ?>/images/post-thumb.jpg” width=”196″ height=”110″ alt=”<?php the_title_attribute(); ?>” /><?php the_title(); ?></a></div></li>
Yeah, I wondered why the code malfunctioned. Thanks.
Yah totally my fault. First tutorial =)
Hi Carina,
is there any chance to tell me how to display only the first image and for the other three only the links in an ul?
echo ”; in single.php should be changed to echo ”;
ehhhh you need to close out the the div i.e. ul AND then div
amazing ,, i was looking for some thing like this ,, i would say thanks for sharing
I keep getting an error from the single.php code:
Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’
With this line of code:
echo ‘Related Posts’;
Not sure if it is just my wordpress page or everyones?
Don’t worry – I got it sorted – I changed the php around bit and got it to display a couple of posts.
Great code, just you need to correct the closing tag position of div#relatedposts
I tried using this code in wordpress 3.2.1 and while in debug mode I got the error
“Notice: WP_Query was called with an argument that is deprecated since version 3.1! “caller_get_posts” is deprecated. Use “ignore_sticky_posts” instead. in /Applications/MAMP/htdocs/wordpress/wp-includes/functions.php on line 3466″
…
it seemed to be working properly but I switched out the caller_get_posts for ignore_sticky_posts, which as it turns out is basically the same thing as caller_get_posts. Is there a reason you were using the deprecated code?
Awesome tutorial! Do you think you could post code that would grab related posts by category? My theme uses a “featured” tag for the homepage’s jQuery slider, and I don’t want those featured posts showing up as related (they never are). Plus, my tags are almost always specific to the post.
Thanks a bunch! This was really helpful, with some customization you can fit that stuff in any template.
Works like a charm.
I am currently using Best Related Posts to show related post with thumbnail. I need to try your steps
Planning to reduce my Plugin usage in WordPress blog
This tips takes me 30 min .but it is awesome way to style related post.It catches the visitor eyes.
Its nice tutorial
Its always advised to reduce WP Plugin usage. I am going to give a try to this Related Post.
Thanks for this, it was just what i needed.
Where i can put The Css ? just put on styles.css ?
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?