Related Thumbnails with YARPP

I’ve been using YARPP (Yet Another Related Posts Plugin) for some time to add a short list of related links to the end of all posts on this site. The plugin works great, and is written by the capable Mitcho (who gave a very good presentation at WordCamp San Francisco).

I was thinking about the post thumbnail feature of WordPress and wondered if I could get thumbnails to appear instead of text links. A bit of searching later and it seems I wasn’t the only one to think of this, but I thought I’d give my take on it, and explain how I ended up with something that looks like this:

Note the the code given below is for 100 pixel thumbnails. This fits the Twenty Ten theme, but may need modification to fit other themes. The code is very simple and make’s no attempt to provide for configuration – you’ll need to edit as appropriate (generally just changing 100 to another value). Consider this experimental – if it works for you then great.

YARPP Template

Conveniently YARPP provides custom templates which allow you to use PHP to display the related posts. Even better, the templates make use of all the standard WordPress template tags so really there’s nothing extra to learn.

What follows is a bit of code that attempts to generate a thumbnail for a post from either the featured image, or from the first image attachment. If no thumbnail can be generated then the thumbnail turns into a short excerpt of the post.

<?php /*
Related Thumbnails
Author: John Godley
*/
?>

<h4 class="meta">You may be interested in:</h4>

<?php if ($related_query->have_posts()):?>

	<ol class="related-posts">
		<?php while ($related_query->have_posts()) : $related_query->the_post(); ?>

			<li>
				<?php
					$img = '';
					if ( has_post_thumbnail() ) {
						$img = get_the_post_thumbnail( $post->ID, 'related-thumbnail', array( 'title' => $title, 'alt' => $title ) );
					}
					else {
						$attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image',  'numberposts' => 1 ) );

						if ( count( $attachments ) > 0 ) {
							$img = array_shift( $attachments );
							$img = wp_get_attachment_image( $img->ID, 'related-thumbnail', true );
						}
					}

					$extra_class = '';
					if ( $img == '' ) {
						$img         = wp_html_excerpt( get_the_excerpt(), 40 );
						$extra_class = ' related-thumb-text';
					}
				?>
				<div class="related-post">
					<div class="related-thumb<?php echo $extra_class; ?>">
						<a href="<?php the_permalink() ?>" rel="bookmark">
							<?php echo $img; ?>
						</a>
					</div>

					<div class="related-title">
						<a href="<?php the_permalink() ?>" rel="bookmark">
							<?php the_title(); ?>
						</a>
					</div>
				</div>
			</li>

		<?php endwhile; ?>
	</ol>
	<div style="clear: both"></div>

<?php endif; ?>

This needs to be added into your theme directory with a filename yarpp-template-thumbs.php. You can download the file here:

yarpp-template-thumbs.zip

Styling the Thumbnails

To accompany the template you’ll also need to add some CSS to your site. This could be added to your theme’s style.css, or any other CSS file that is included on your pages.

.related-posts {
  list-style-type: none;
  margin: 0;
  height: 110px;
}

.related-posts li {
  padding: 0; margin: 0;
  float: left;
  margin-right: 5px;
}

.related-post {
  position: relative;
  padding: 3px;
  background-color: white;
  border: 1px solid #ddd;
  width: 100px;
  height: 100px;
  overflow: hidden;
}

.related-post:hover {
  border: 1px solid #999;
}

.related-title {
  position: absolute;
  bottom: 3px;
  left: 0;
  font-size: 0.7em;
  width: 96px;
  margin-left: 3px;
  opacity: 0.5;
  padding: 1px 2px;
  text-align: center;
  line-height: 1.4;
  height: 30px;
  overflow: hidden;
  background-color: black;
  font-family: helvetica, arial;
}

.related-title a {
  text-decoration: none;
  color: white;
}

.related-thumb {
  font-family: courier;
  background-color: white;
  font-size: 1.2em;
  line-height: 1.2;
  height: 100px;
  overflow: hidden;
  width: 100px;
}

.related-thumb a {
  text-decoration: none;
  color: #ddd;
}

You will also need to add the following code to functions.php in your theme to get WordPress to generate appropriately sized thumbnails:

add_image_size( 'related-thumbnail', 100, 100, true );

Note that if you are using a thumbnail size other than 100 you must also change the value here.

Creating Your Thumbnails

Although I specified a thumbnail size of 100 pixels with add_image_size(), WordPress won’t automatically generate these images for existing posts. Instead you’ll need to use a plugin such as Viper007Bond’s Regenerate Thumbnails to go back through your attachments and create the thumbnails. If your chosen size already exists on the Settings > Media page then you can skip this stage.

Putting it Together

The final step is to configure YARPP to use the new template.

That’s it! Related post thumbnails with a fallback for posts without images. One nice feature is that you can upload an image to a post and it will be used as the thumbnail, regardless of whether you actually use the image in the post itself.

Hopefully this is useful to someone. If you have any good modifications then please do let me know.

29 comments

  1. Nice tutorial, I managed to get it working except I am not getting any thumbnails 🙁 not sure what I am doing wrong as I followed the instructions, and regenerated thumbs for older posts aswell.

  2. I’ve been trying to setup related posts thumbnail on my blog but I am failing again and again.. Any help??

  3. This is far easier than using other methods I’ve tried, thank you.

    One thing, how can I create a cropped thumbnail, instead of reduced scale images?

      1. Actually, that “true” value at the end of:

        add_image_size( ‘related-thumbnail’, 100, 100, true );

        will hard crop the photo rather than scale it, so that should actually give you the cropped thumbnail (once you use regenerate thumbnails, of course).

  4. Hi, pleasure to have encounter this tutorial. I have an enquire, while this is the latest article with regard to the post_thumbnail function in WordPress 3.x, how do I display it exactly like LinkWithin?

  5. Thanks mate, working nicely. Anyone have any thought on how to add a default fallback image, as opposed to a text string where there is no image present?

  6. where exactly do I have to add the “add_image_size( ‘related-thumbnail’, 100, 100, true );” ?
    putting it at the end doesnt work
    newbie here 🙂

      1. I’m having the same issue as May. When I put it at the end of the functions.php file, it just shows the text at the top of the page. Where exactly in the functions file should it go?

  7. I want to change the color of the text that says, “related posts.” Is this possible? So that the color of the text won’t match the color of the text content. Can you teach me how?

  8. Actually I just discovered that the related-post content inherits CSS properties from my post-content tag. Is there a way to detach this manually ?

  9. In case anyone else gets an error, make sure you have the following line in your functions.php:

    add_theme_support(‘post-thumbnails’)

    Great post, thanks!

  10. John,

    This is great!

    I updated my child theme’s style.css with your code and uploaded the yarpp-template-thumbs.php to my child theme’s directory as well.

    However there seems to be a problem with the way the add_image_size() function is handled. What I did is that I copied your line of code into my functions.php file, all the way at the end, just before the ?>

    Now without the code in functions.php, it seems to work but the thumbnail is not ligned up correctly. But with the changed functions.php, uploaded into my wp-includes directory, when I open the page I get the following error:

    Fatal error: Call to undefined function add_image_size() in /public/sites/www.indexvolger.nl/wp-includes/functions.php on line 4688

    Please advise how to handle the functions.php piece of code (newbie mode please :-))

  11. Hi, I was looking for something just like this, but my thumbnail are 125×125, and that’s good for me.

    However, this template is showing the featured image in full size, not the 125×125 version… Is this something I can fix?

    1. I have added

      add_image_size( ‘related-thumbnail’, 125, 125, true );

      To my functions.php. I set it to 125×125 in media and even rebuilt the thumbs again. But it is still showing the featured-image in full size (resized by CSS)

      1. Figured it out 😉

        My theme has a custom-functions.php but adding the code there didn’t work. It had to be added to the main functions.php. I’ll contact the theme maker about this.

  12. Hi!

    Already left this page, but forgot to say thank you. So, thanks you!

    Works perfect.

    Cheers.

  13. Sad day! I’m a complete newbie in all of this stuff and I can’t seem to find any tutorials that talk me through the process as if I’m a two-year-old. Do you have any suggestions? I don’t even know how to add things to a theme directory.

  14. My site is NSFW… just warning ya.

    Why is it that the first image in the post is not always grabbed for the thumbnail? I would like for YARPP to display the first image in each post as the thumbnail.
    Thanks.

Leave a comment

Your email address will not be published. Required fields are marked *