Automatic WP Thumbnails & Proportional Excerpts
108Automatically 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:
- One on the left side with the thumbnail.
- And one the right side for the text.
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,'[»]','<strong><em><b>','span','no'); } else { the_excerpt_rereloaded(45,'[»]','<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,'[»]','<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.
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!
Enjoy this post? You should follow me on Twitter!
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.
I’m ok too with CSS, but I need to improve my PHP skills. Anyway, I bookmark this for colleagues!
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.
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.
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.
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.
I concur that on face value it seems strange since WP has the functionality built into the core but timthumb is much more robust. As a hands on type that created my own WP site, getting the right thumb seems intuitive but I do often get questions about it and watch peers and friends struggle with the built in WP functionality.
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.
@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.
why not use the_postthumbnail(width,height)?
Can you be more specific Paul ? Is that a core wp function ?
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?
I do use timthumb, at the beginning of the post “We will also need the TimThumb script…”
oh – got it, thanks! (lol) I saw the ncode image resizer at the end…
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
Hhoah! very applicable tuts, it’s something we commonly meet on web project. thanks! :D
Anyway, thanks for linking to my post ;)
Expert post,very cool
Thanks a lot
Yes, I found it very clear too, very nice post!
The codesnippet and the text don’t match
Is it zc=0 or zc=1 ?
True, the parameters for the timthumb script should be “w=243&zc=1&q=70”.
Damn, i meant “zc=0”. I copied the code but didnt change the value.
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.
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.
wow its great,
It would be nicer to use core WordPress features in my opinion.
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.
Yeah, using core wordpress features is much better.
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
great post, thanks, kevin.
Just try to learn some design for wp, thanks.
Amazing post, thanks for this tutorial.
Awesome post you have shared. I will try it. Thanks for the tutorial.
It is great, congratulations for this post.
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.
Doesnt it cut the text of the excerpt ?
Really Interesting, keep the good jop
thanks for the tutorial, would be interesting to test
Thanks for this tutorial. its great.
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!
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.
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 ;)
thanks for this info, its so nice article i think,but the thumbnile is cropped or resized?
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.”
Great info. Can’t wait to try it out.
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.
I thinks it’s will be better if you query run in WordPress standard query. Is it possible?
Everything’s possible with wordpress. Being serious, i didnt get your question Jauhari.
Thanx. Very nice
Great tips Kevin! Thanks!
Thanks for comments dellopos & W3mag, appreciated.
Hi,
How about using a wrapper to limit the thumbnail size and position?
I guess its possible with wordpress, right?
Yeah might be possible, but the goal was to get the proportion between the image size and the excerpts’ lenght.
This is not working for me. My images are hosted in a subdomain. Please help me.
In my experience, timthumb doesnt work with images hosted outside the main domain. Your subdomain is on the same ftp ?
Yes My subdomain is on same FTP.
This is extremely helpful. Thanks for putting the tutorial together.
This is a really good post, thank you so much. Well worth bookmarking.
Andrew.
Wow, great. This easy gives a wp blog a professional and clean look with less work for authors. Thanks for sharing!
anlatım için teşekkürler
Çok güzel bir çalışma olmuş
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
Helpful post. Thanks for this idea !
This is a great tutorial with in depth code and explanation. Thanks for Sharing
good idea.. I like it
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.
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.
Expert post,very cool
very nice…will use soon
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?
Easy! send me a message via YOEBO.com ;)
Like here is problogdesign they have many fabulous screenshots that’s why many are coming again and again to watch out for new post!!
Could I automatically grabb thumbnails from all posts in a particular category?
I usually do go through the spam filter, so even the simple fact you have a Gravatar
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
wow its great
when using autoblog with this its can make more easy :D
Is there a way to make the size of the picture smaller (not only the size that is presented) but the actual size so that it loads quicker?
I use a pluin that automatically takes the first image from each post but forces it to be a certain size without changing actual size. As a result the size of the page is very big.
Any suggestions would be much appreciated.
This solution is also using a script that resizes the picture rather than loading a smaller version. The positive point is that the big size is already loaded in the cache for further uses. But true it does load a small size of the big one.
Would maybe be interesting to try to work with wordpress’ auto generated pictures. During the upload, wordpress does create different sizes of a single picturer, your solution could be in this direction.
That’s cool and innovative..
Hi,
Nice tutorial … since i do like customizations a lot i simply like this .. but the problem is it is not working .. when i went through firebug the link is there .. for eg:
but cant find the image … should i create a cache folder for working with timthumb ..?
yeah, check your ftp first to see if there is a folder named “cache” in your theme’s directory (if timthumb.php is directly in the folder). If not, create it and try a refresh or a new picture upload in the wp admin.
Never thought about doing this, I’ll try to use this with autoblog.
I’ve been looking this guide for a long time.
Now when i’m here, it’s awesome. You help me a lot.
Thank you in advanced :D
this is really great code but the problem is when i am using the function like this inside the loop then i am getting this error
Warning: strpos() [function.strpos]: Offset not contained in string in C:\wamp\www\eventeve\partyideas\wp-content\themes\twentyten-vaseem\functions.php on line 894
i am using the function like this
getImage(‘2’);
You’ve tried with getImage(‘1’); ?
Nice post ! Rather technical as you said but very practical. Thanks again.
Thanks for the info. I understand CSS , but I still have some problems with php. With this type of stuff, you’re helping me a lot.
Great solve for a customer request. Definitely don’t think that there is an easier way to recreate this with core.
I can’t believe this is even possible. All I’ve done on my site is made the thumbnails one cropped size and just enough text set in length by letters to be the same height.
Thanks Kevin,
Love you tutorial, and have just set up everything on my site, seems to works pretty fine.
wow, one again you make great turorial, thanks for sharing dude :)
That’s cool and innovative..
Thank for your shared ^ ^
Thank you for your article is wonderful
Nice tutorial. much more useful for autoblogs.have been looking for this quite sometime.
Very useful post. Your current Website style rocks as well!
Thanks for the comments guys!
Nice post Kevin. I can try this now, thanks for the tutorial..
Soccer is my favorite,so is David Beckham
Thanks for article. Great article…
I have 2 other blogs that are like 2 versions
Excellent post, Thanks your article was really interesting and it was very relevant to for answering my questions will definitely read more of your posts in the future
It is great to have the opportunity to read a good quality article with useful information on topics that plenty are interested on.I concur with your conclusions and will eagerly look forward to your future updates Finace Software
Will this work on WP 3?
after I learn thumbnails code that you teach in your post, my website has become further beautiful and full with table of contents. thanks.
There are many things should be taken into consideration, but you’ve made a good point here. Thanks a lot for that. I will follow your way soon.
good and nice to think
This is such an informationrmative article and very clearly written. Every single thought and idea is direct to the point. Perfectly laid out. thank you for taking your time sharing this to you readers.
I have to use this for my site