Automatic WP Thumbnails & Proportional Excerpts

pic

Automatically grabbing thumbnails from posts is cool. But what about automatic excerpt lengths that match the height of those photos?

I recently redesigned a blog for a client and it had an automatic thumbnail for each post, with a fixed length excerpt beside it. It was okay, but our client didn’t like the fact that it was “cutting” his pictures off sometimes. Our goal then had 3 steps:

  • 1 – To set a thumbnail’s height proportional to the original picture, so that we would not cut parts of it off.
  • 2 – Use this height value to display excerpts about the same size.
  • 3 – Set up an automatic Lightbox on images that are too large for the content area.

Of course all of this had to be automatic, custom fields are cool for us designers/programmers, but for clients it’s too much hassle.

That’s what I’m going to teach you to do in this post.

NB – This is going to get quite technical; you’ll need to have had some experience editing theme files before, and a little HTML/CSS.

Examples

Let’s start with an example of exactly what we are going to be done. Check out the screenshot below, or see the demo site (Notice how each excerpt is a different length, depending on the thumbnail?).

And here, is an example of the automatic lightbox effect.

All good now? Okay, let’s see how it goes.

The last thing to note; this whole process is based on Fikri Rasyid’s post here at Pro Blog Design.

We will also need the TimThumb script in our WordPress theme. Just grab it from here and upload it to your theme directory.

Index.php

In index.php or home.php, depending on you WordPress theme, you’ll have your WordPress loop. You’ll need to add in 2 divs for aligning the two sections of the posts:

  1. One on the left side with the thumbnail.
  2. And one the right side for the text.

pic2

Here goes the code we will use for the thumbnail:

<div class="thumbnail">
<a title="<?php the_title_attribute('before=Permalink para: '); ?>" href="<?php the_permalink(); ?>">
<img src="<?php bloginfo('template_url'); ?>/timthumb.php?src=<?php getImage('1'); ?>&w=243&zc=1&q=70" alt="" />
</a></div>

We use the Timthumb script and the function getImage (You’ll be adding that function to your functions.php later on, don’t worry about it just yet) to return a thumbnail of 243px width and a proportional height.

The 243px is just an example that fitted my design, you can of course set any size you want within the Timthumb parameters: &w=243&zc=0&q=70.

And for the text:

<div class="excerpt_home">
<?php 
$postid = $post->ID;
$query = sprintf("SELECT * FROM wp_posts WHERE id='%s'",
mysql_real_escape_string($postid));
$result = mysql_query($query);
$row = mysql_fetch_array($result);
 
$w = $row[post_content];
$w2 = explode("width=\"", $w);
$w3 = $w2[1];
$w4 = explode("\"", $w3);
$width = $w4[0];
 
$h = $row[post_content];
$h2 = explode("height=\"", $h);
$h3 = $h2[1];
$h4 = explode("\"", $h3);
$height = $h4[0];
 
if($height != 0 && $width != 0) {
 
$t1 = ($height*100)/$width;
$t2 = (243*$t1)/100;
$t3 = ($t2*28)/100;
 
the_excerpt_rereloaded($t3,'[&raquo;]','<strong><em><b>','span','no');
}
 
else {
the_excerpt_rereloaded(45,'[&raquo;]','<strong><em><b>','span','no');
}
 
?>
</div>

About this code:

  • We first grab the ID of the current post.
  • Then we search the database for the original picture’s size.
  • And we display the text.

WordPress saves in the database the width and height of each picture in a post. The idea is to grab those values to achieve our goal. We need the content of post_content, in the table wp_posts. We then search for the text width=’ to grab the value until we meet the closing .

This is all achieved with these lines of code:

$w = $row[post_content];
$w2 = explode("width=\"", $w);
$w3 = $w2[1];
$w4 = explode("\"", $w3);
$width = $w4[0];

We do the same for the height of the picture:

$h = $row[post_content];
$h2 = explode("height=\"", $h);
$h3 = $h2[1];
$h4 = explode("\"", $h3);
$height = $h4[0];

If those values are not empty, it means that we have a picture.

We then use a proportional function to give the variable $t3 a value for the the_excerpt_rereloaded function. I use this plugin to display a custom ‘Read more’ text: [»] (You’ll need to install the plugin to get the code above to work because it is what lets us change the length of the excerpt)

$t1 = ($height*100)/$width;
$t2 = (243*$t1)/100;
$t3 = ($t2*28)/100;

243 is the width of my final thumbnail, and 28 is the proportion for the text. Why? Because $t2 will give me the height of the picture in pixels and the parameter for the_excerpt_rereloaded is a number of words. Without this division $t3 = ($t2*28)/100; my text would be proportional, but way too long.

Feel free to adjust those values to make the excerpts line up perfectly with your own line lengths!

Finally if no picture is found i display a 45 word excerpt because it suits my default picture:

else {
the_excerpt_rereloaded(45,'[&raquo;]','<strong><em><b>','span','no');
      }

Of course if the text of the post is too short, it wont fit the whole div on the home page.

functions.php

Here is the function getImage() to put in functions.php in our WordPress theme:

<?php
// retreives image from the post
function getImage($num) {
global $more;
$more = 1;
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$image[$i] = $postOutput;
$start=$imgEnd+1; 
 
$cleanF = strpos($image[$num],'src="')+5;
$cleanB = strpos($image[$num],'"',$cleanF)-$cleanF;
$imgThumb = substr($image[$num],$cleanF,$cleanB);
 
}
if(stristr($image[$num],'<img')) { echo $imgThumb; }
else {echo bloginfo('template_url')."/images/padrao_w.png";}
$more = 0;
}
?>

As I said before, this is from Fikri’s post.

I just modified it at the end to add a default picture if the post does not contain any. In my case, the picture is located in the images folder of my WordPress theme: /images/padrao_w.png. Again, adjust that to your own default image link!

Lightbox system

This last section is much easier; I just used the nCode Image Resizer plugin. It checks if the picture in the post is bigger than 630px width. If yes, it does resize it proportionally to 630px width and puts link above the image to zoom within the same page.

Lightbox link

Just go the WordPress admin panel to set the width option to whatever value suits your theme.

Conclusion

This method might not be the only one to achieve this and also not the best ever. I’m pretty sure it can be improved.

Do not hesitate to post comments about it, I’d be glad to help and maybe improve the system.

And of course, if you do implement this on your site, share the link with us!

Share

  1. Chris Mower (5 comments)22 April 10

    This is some sweet stuff! I understand CSS just fine, but I still have a ways to go with php. I usually hire out for that. With this type of stuff, you’re helping guys like me out a ton! Thanks.

  2. jeherve (2 comments)22 April 10

    Nice idea, that definitely looks good. However I do not really understand the choice of timthumb for the thumbnails, when WordPress natively handles thumbnails and cropping in a really simple way since WP 2.9.
    It would be nicer to use core WordPress features in my opinion.

    • Derek (3 comments)22 April 10

      Makes more sense to go with something like timthumb for themes rather than relying on the WordPress thumbnail engine for distributable themes. Using timthumb the developer / designer has control without forcing the theme user to change their WordPress install settings.

    • jeherve (2 comments)22 April 10

      I am not sure I follow you entirely here. There is no need for the user to change their WordPress install settings. Size and cropping of the different thumbnails can all be set in the functions.php, defined by the theme author.

      Check out Mark Jaquith’s blog, he wrote about it when the feature was launched, at the end of December.

    • Ched (2 comments)25 April 10

      Timthumb is much better at cropping/resizing images. You can adjust the dimensions on the fly: no need to delete and re-upload an image just for it to count as an ‘attachment’.

      IMO, post_thumbnail is not better (yet). Timthumb is still more flexible to work with, and much easier for for the blogger when it comes to using images in their posts.

  3. Keith Davis (71 comments)22 April 10

    Hi Kevin
    No way could I comment on the PHP but I love the idea of thumbnails.
    Fortunately my theme uses timthumb (clever name) for displaying different size thumbnails in different areas and the result is very pleasing.
    What is my theme?
    Take a look at the top of this page on the right hand side. Spot the word “Elegant”?
    Click that for some great themes with thumbnails already sorted.

  4. kevin (40 comments)22 April 10

    @jeherve, if i do remember well (did this solution around 5 months ago), i think i created this solution for wp 2.8.x. But that would be interesting to see if it could be done without timthumb as you say.

    @Chris, glad to help ;)

    @Keith, yeah i know elegant themes, some nice stuff.

  5. paul (13 comments)22 April 10

    why not use the_postthumbnail(width,height)?

  6. This is a great tutorial with in depth code and explanation. Any reason you used the thumbnail script you did and not something like the timthumb script that most theme designers seem to use? Does yours have advantages?

  7. Pippin (60 comments)22 April 10

    I really like what you’ve done here. I’ve run into the same problem of matching excerpt heights to thumbnails, especially as, for example, a 100 word excerpt is not always exactly the same height, thanks to word length.

    I would also take it one step further and incorporate the excerpt_rereloaded plugin into the functions.php, so that you can remove the dependency of a plugin. Really great for themes. I showed how to do this here

  8. Fikri Rasyid (40 comments)22 April 10

    Hhoah! very applicable tuts, it’s something we commonly meet on web project. thanks! :D

    Anyway, thanks for linking to my post ;)

  9. Dat Tai (2 comments)22 April 10

    Expert post,very cool

    Thanks a lot

  10. TeMc (3 comments)22 April 10

    The codesnippet and the text don’t match

    Is it zc=0 or zc=1 ?

    • kevin (40 comments)23 April 10

      True, the parameters for the timthumb script should be “w=243&zc=1&q=70″.

    • kevin (40 comments)23 April 10

      Damn, i meant “zc=0″. I copied the code but didnt change the value.

  11. Nice tutorial. But I have a problem with this method: when we search for the width and height of image in the database, it’s ok if the post has images, but what happen if we use the post thumbnail feature of WP 2.9 to show the thumbnail in homepage.

    BTW, it’s much more easier if the height of the thumbnail is fixed. I see many bloggers fix this value. And we don’t need to look at database to find width, height and do some calculations, etc.

    • kevin (40 comments)23 April 10

      This has been developped for wp 2.8.x so i don’t know what happens with this feature you’re talking about, would be interesting to test.

      Yes it’s much easier if the thumbnail is fixed, but as said in the post, it was a client’s request and we basically had to do it, it’s a new and quite important client for our company.

  12. memey (3 comments)24 April 10

    wow its great,

  13. sumaru (2 comments)24 April 10

    It would be nicer to use core WordPress features in my opinion.

    • Pippin (60 comments)24 April 10

      You have a point; it would be nice to have this sort of feature while only using core WordPress Features. However, accomplishing the sort of thing Kevin has done here is not possible, or not as effective with core-only features.

  14. Yeah, using core wordpress features is much better.

  15. raksamuda (1 comments)24 April 10

    I do not understand css php language and I intend to learn. I hope I can follow this blog to learn more about php and css

  16. Elvis (10 comments)26 April 10

    great post, thanks, kevin.
    Just try to learn some design for wp, thanks.

  17. Whois (3 comments)26 April 10

    Amazing post, thanks for this tutorial.

  18. John Smith (3 comments)30 April 10

    Awesome post you have shared. I will try it. Thanks for the tutorial.

  19. It is great, congratulations for this post.

  20. This is a nice little tuturial. What I do is just make the div container the same height as the image thumbnail and than simply limit the amount of characters in the excerpt as follows:

    This is not a perfect solution (won’t always match the exact height), but its an easy alternative.

  21. Oraculus Info (2 comments)2 May 10

    Really Interesting, keep the good jop

  22. mariana (2 comments)3 May 10

    thanks for the tutorial, would be interesting to test

  23. Marionn (1 comments)4 May 10

    Thanks for this tutorial. its great.

  24. RAR Downloads (18 comments)5 May 10

    Thanks for the tutorial and the plugin, but I have theme that resize images automatically and doesn’t have this function in functions.php, I don’t know how it work!

  25. Randy (2 comments)6 May 10

    Really detailed article! Nicely done.
    I notice you use mysql_query() over the wpdb->. Is this always your preferred method? I’ve always wondered because it seems easier to me being more familiar with mysql_query().

    On a side note, your portfolio is very unique! I love it.

    • kevin (40 comments)6 May 10

      Thanks for the nice words. About the mysql_query, am not a big php developper so i reached this method that happened to work and as said at the end of the article, am not sure it’s the best way ever. Worked for me, and as i have a lot of things to do, i didnt have time to try to think about something else. If you think of something else to improve it, i’d be glad to hear about ;)

  26. thanks for this info, its so nice article i think,but the thumbnile is cropped or resized?

    • kevin (40 comments)7 May 10

      Resized but not cropped, as said in the beginnign of the post: “1 – To set a thumbnail’s height proportional to the original picture, so that we would not cut parts of it off.”

  27. Leah (5 comments)7 May 10

    Great info. Can’t wait to try it out.

  28. This is really a solid article. One of the biggest concerns when laying out a blog section is how the excerpt/read more functionality will play out. You always want to use a snippet of some sort and not display the whole article. Otherwise, you may run into duplicate content issues.

  29. Jauhari (11 comments)10 May 10

    I thinks it’s will be better if you query run in WordPress standard query. Is it possible?

    • kevin (40 comments)22 May 10

      Everything’s possible with wordpress. Being serious, i didnt get your question Jauhari.

  30. dellopos (3 comments)21 May 10

    Thanx. Very nice

  31. W3Mag (1 comments)21 May 10

    Great tips Kevin! Thanks!

  32. kevin (40 comments)22 May 10

    Thanks for comments dellopos & W3mag, appreciated.

  33. penny auctions (24 comments)1 June 10

    Hi,
    How about using a wrapper to limit the thumbnail size and position?
    I guess its possible with wordpress, right?

    • kevin (40 comments)2 June 10

      Yeah might be possible, but the goal was to get the proportion between the image size and the excerpts’ lenght.

  34. Tanmay (2 comments)2 June 10

    This is not working for me. My images are hosted in a subdomain. Please help me.

    • kevin (40 comments)2 June 10

      In my experience, timthumb doesnt work with images hosted outside the main domain. Your subdomain is on the same ftp ?

  35. Tanmay (2 comments)2 June 10

    Yes My subdomain is on same FTP.

  36. This is extremely helpful. Thanks for putting the tutorial together.

  37. This is a really good post, thank you so much. Well worth bookmarking.
    Andrew.

  38. Holger (2 comments)13 June 10

    Wow, great. This easy gives a wp blog a professional and clean look with less work for authors. Thanks for sharing!

  39. Wordpress (3 comments)16 June 10

    anlatım için teşekkürler

  40. Çok güzel bir çalışma olmuş

  41. Lou Sparx (4 comments)21 June 10

    Great article! I need some help, I don’t mind about thumb size to match the text all I want is to be able to grab a thumb from the main (big) image in the post and display it in the excerpt on the home page?

    I’m willing to pay for an answer/code without the use of a plugin that messes with my other plugin that grabs my excerpt lol.

    How do I automatically show a thumbnail (of the main post image) in the post excerpt?

    Please help,
    Louis

  42. Css Design (2 comments)26 June 10

    Helpful post. Thanks for this idea !

  43. JhezeR (6 comments)27 June 10

    This is a great tutorial with in depth code and explanation. Thanks for Sharing

  44. jurug (10 comments)11 July 10

    good idea.. I like it

  45. Credit Cards (4 comments)14 July 10

    Great tips, although most paid these come with this feature built in. I guess i will just use this to “tweak” my other sites with free themes.

    • kevin (40 comments)14 July 10

      Never seen this feature in any theme, that’s why i built it. If you know some themes with this i’d be interested to see that.

  46. It’s a precise and informative article. Things are formed symptom less. Get to know lot’s of artifact which were unbeknownst to me. It’s truly one of the most facilitative article I get ever read. Thanks for to percentage sensing for author from you. Symmetrical I bookmarked this diplomat as asymptomatic for to get supply from it in incoming.

  47. web design (27 comments)16 July 10

    Expert post,very cool

  48. very nice…will use soon

  49. Nicole (4 comments)23 July 10

    Could I automatically grabb thumbnails from all posts in a particular category? I would like to present a category with a list of each post under that categoty. I would love to present each post as you have done here (wiht the tumbnail). Is this possible? Could this method be used to do this?

  50. Lou Sparx (4 comments)24 July 10

    Easy! send me a message via YOEBO.com ;)

  51. joyería (4 comments)27 July 10

    Like here is problogdesign they have many fabulous screenshots that’s why many are coming again and again to watch out for new post!!

  52. Paula Dalesio (22 comments)29 July 10

    Could I automatically grabb thumbnails from all posts in a particular category?

  53. Desarrollo web (13 comments)29 July 10

    I usually do go through the spam filter, so even the simple fact you have a Gravatar

  54. Camisolas (5 comments)31 July 10

    based on the photoshop default picker. But you can use it to create color palettes and save them for future use. Also, you can download the palettes that you create as

  55. darnals (6 comments)13 August 10

    wow its great
    when using autoblog with this its can make more easy :D

Leave a Comment

Your reply will be added to the comment above (Below any other replies to this comment) -

(We DoFollow)

Not sure how to get an image with your comment?