Display & Style Related Posts For Your WordPress Site

Display & Style Related Posts For Your WordPress Site

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

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://joshriser.com Josh Riser

    Will any of this code work with all the lines commented out? Most of the code you have is commented out by double slashes (//).

    • http://owenconti.com Owen Conti

      I have a feeling that’s on purpose, so you can’t copy n’ paste.

      • Al

        doubt that, seems kinda silly to be doing that in a tutorial

        Al

        • Brandon Jones

          True – it was just our code highlighter acting up – it’s been removed now ;)

  • http://www.paulund.co.uk Paul

    Is it better to get related posts by tags or by category?

    • http://www.sigididesign.com Vezu

      I think it depends on your application.

      • http://www.paulund.co.uk Paul

        I mean in terms of click-through rate is it preferred to be related tags or category?

  • http://www.guillaumevoisin.fr/ Guillaume

    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.

    • http://www.paulund.co.uk Paul

      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.

      • http://affanruslan.com Affan Ruslan

        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.

        • http://twitter.com/GemmaWeirs Gemma W.

          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.

  • http://www.iteracion.cl felipe

    very nice, great post.

    thanks,

    saludos,
    Felipe…..

    • http://www.kstudiofx.com Carina Javier
      Author

      thank you very much!

  • http://www.kstudiofx.com Carina
    Author

    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!

  • http://wellvisualarts.com Well

    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?

    • http://www.kstudiofx.com Carina Javier
      Author

      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() ?>

  • http://zetha.tk zetha

    how i can add at blog home ?? or somethink like ads under navigation on this site ? please help me ..

    • http://www.kstudiofx.com Carina Javier
      Author

      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?

  • http://www.kstudiofx.com Carina Javier
    Author

    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>

    • http://whysodumb.com Abhimanyu

      Yeah, I wondered why the code malfunctioned. Thanks. :)

      • http://kstudiofx.com Carina Javier
        Author

        Yah totally my fault. First tutorial =)

  • Pingback: [wp] related post | code@butterflybone

  • Pingback: Display & Style Related Posts For Your WordPress Site

  • Pingback: WordPress Theme Lesson 10: Related Posts, Dealing with Nested Loops | AcornArtwork Blog

  • Cornel

    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?

  • eric

    echo ”; in single.php should be changed to echo ”;

    • eric

      ehhhh you need to close out the the div i.e. ul AND then div

  • http://8mediaeg.com 8MEDIA

    amazing ,, i was looking for some thing like this ,, i would say thanks for sharing :)

  • http://PSDtutorials.co.uk Peter Sawyer

    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?

    • http://PSDtutorials.co.uk Peter Sawyer

      Don’t worry – I got it sorted – I changed the php around bit and got it to display a couple of posts.

  • http://premitheme.com Ahmed ( premitheme )

    Great code, just you need to correct the closing tag position of div#relatedposts

  • http://jacksonhoose.com Jackson

    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?

  • http://collegeinfogeek.com Thomas Frank

    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.

  • k4

    Thanks a bunch! This was really helpful, with some customization you can fit that stuff in any template.
    Works like a charm. :D

  • http://www.techpraveen.com Techpraveen

    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 :)

  • http://www.tricksforcomputer.com deepak

    This tips takes me 30 min .but it is awesome way to style related post.It catches the visitor eyes.

  • Pingback: Как добавить блок «Похожие записи» на WordPress сайт | Wordpresso

  • http://www.geekyard.com Geekyard

    Its nice tutorial :) Its always advised to reduce WP Plugin usage. I am going to give a try to this Related Post.

  • Chris

    Thanks for this, it was just what i needed.

  • http://toyskiddy.co.cc Kiddy

    Where i can put The Css ? just put on styles.css ?

  • Pingback: Display & Style Related Posts For Your WordPress Site | Unicolored.com

  • http://thereadingclinic.com/ Daniel Lee

    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?

  • Pingback: somedaytest » asdk jibba jabba

  • http://www.jixu.me ptkid

    How to show all the post of which tag then the style like this?Plz…

  • http://www.taylorpennock.com Taylor Pennock

    Couldn’t get this to work until I added:

    global $post;

    at the first.

  • Eric

    Horrific code.

  • Matt Kaludi

    You forgot to close a in line 27

  • holymessagebd.com

    I need this plugin.

  • Natalie

    Hi, where should I add the codes in step 1 if I want to have the related post listed before comment? I’ve added the codes in single.php however, the photo is not appearing properly. Thanks.

  • http://twitter.com/Tame_Geek Mark Thomson

    Is there a way to get this to pull custom post types with the same tags as posts?

  • http://psdesain.net/ Jaka

    it doesn’t work with my theme :(

  • http://www.facebook.com/people/Motti-Bembaron/100000800012828 Motti Bembaron

    Hi,

    in the PHP code (the part that is to be put in the single.php file) It is missing a right after the tag all the way at the bottom.

    Cheers