Automatic Wordpress Thumbnail Without Custom Field

thumbnail-preview

Let’s say you want to show thumbnails in your blog’s front page. A lot of blogs do that now and it’s a good way of making the page look more alive.

The only problem though is that using custom fields can be complicated and time-wasting. This post will show you how to make your theme generate thumbnails automatically, based on your post’s first image.

This trick is done by mixing some wordpress hacks and a php script. The PHP script is Darren Hoyt’s timthumb.php, the hack is WpRecipe’s how to get the first post image.

Together, they’ll grab your image and resize it for you! Let’s get started.

1 – Get the TimThumb.php Script

Get the timthumb.php script and place it on your theme directory. You can either download it, or create a blank timthumb.php file on your theme directory, open the script here, copy, paste it into your timthumb.php file, then save it.

2 – Edit Functions.php

Open your theme’s functions.php file (Or create a file with that name if it doesn’t have one), then paste the code below into it. This will retrieve the URL for the first image in your post. The code written here is based on WpRecipe’s original post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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; }
$more = 0;
}
//retreive image ends
?>

3 – The Thumbnail Code

This is the thumbnail code. This code has to be written inside the_loop. Since the most common use of thumbnail is to be shown beside the excerpt, in this tutorial we’ll paste this code above the_excerpt(); or the_content(); in index.php or home.php file.

1
2
3
4
5
<div class="thumbnail">
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<img src="<?php bloginfo('template_directory'); ?>/timthumb.php?src=<?php getImage('1'); ?>&w=150&h=150&zc=1">
</a>
</div>

The code above will create a 150×150 pixel thumbnail. If you want to change the size of the thumbnail, just change the ‘w’ and ‘h’ parameters. For more info, read the timthumb post here.

4 – Add some CSS Rules

You can style the thumbnail in any way you like, for example, you might add the following to your style.css file:

1
2
.thumbnail a:link, .thumbnail a:visited {display:block; float:left; padding:5px; background:#e2e2e2; width:150px; height:150px; margin:5px 5px 0 0;}
.thumbnail a:hover, .thumbnail a:active {background:#C4C4C4;}

And the result would be something like this:

thumbnail-result

No more custom fields, no more uploading images purely for the thumbnails, no more pain. What do you think? Is the time saved worth it, or do you prefer to craft your thumbnails more carefully?

Share

  1. Does this do anything more than The Excerpt Reloaded plugin?

    • The excerpt reloaded plugin deals with the excerpt (text), while this hack deals with how to pull off content’s first image and resizes it. So, it’s different :)

    • Excerpt reloaded handles first images as well as text! Not sure about the resizing aspect, but I’ve been using it for years to display text and images on my homepages.

    • Jon (9 comments)15 October 09

      Yah, it’s not a plugin.

    • Kim (2 comments)30 October 09

      Thanks for sharing this…
      I am using Wordpress as a CMS for a client and needed to have thumbnail images load automatically to post excerpts without the need for the client to have to deal with custom fields.
      This works like a charm!

    • Nowell (1 comments)21 January 10

      Muy buenooo

  2. G.Han (5 comments)5 October 09

    Great post,very handy!!! Thanks for sharing!!

  3. Andrea_R (19 comments)5 October 09

    I’d prefer to use the get_the_image plugin instead. Timthumb makes new thumbnails – why not use the thumbnails WP has already generated?

    Otherwise, yay! :D Good post.

    • I’ve used the get_the_image plugin. The plugin pull the thumbnails WP has already generated. And the problem is, WP only create 150 x 150 thumbnails (or any other exact size after you re-set it). If you want to create -for example- 150 X 50 px thumbnail, you’ll need this hack. ;)

  4. Thanks – I used timthumb a long time ago but have kind of forgotten about it. The get_the_image plugin is nice as well.

  5. Cinq (3 comments)6 October 09

    How does this remove the -tag from the_content() ?

    • excuse me, can you give us a clearer point? The explanation of how does the hack get the image address is in step no.2. :)

  6. Sebbi (1 comments)6 October 09

    Doesn’t wordpress allready generate thumbnails when I upload an image? Information about these thumbnails can be found in the attachments of a post …

    In code:

    $imgurl = “”;
    $files = get_children(“post_parent=”.$postid.”&post_type=attachment&post_mime_type=image&orderby=menu_order”);
    if($files) {
    $keys = array_keys($files);
    $num=$keys[0];
    $imgurl = wp_get_attachment_image($num);
    }

    Drawback: no indiviuals widths and heights …

    • Because the thumbnail wp has generated is 150 x 150 px image. If you want an 150 x 50 px for ALL of your posts automatically, you know why you’ll need this hack.

      You can set the width and height on step no.3. See the src=”..”. set width thru w= and height thru h= . For more detail information, you can check Darren Hoyt’s explanation on timthumb’s page: http://www.darrenhoyt.com/2008.....-released/

  7. vinoth (5 comments)6 October 09

    WoW… i was searching for this hack and now you gave it.. Thank you Fikri Rasyid

  8. ia (1 comments)6 October 09

    Regarding the 150×150 default thumbnail, I thought you can change those dimensions in the settings page?

    I’m all for dynamic resizing of images though. I don’t need WP to create multiple images every time I upload a new one and I wish WordPress had chosen this method instead.

    • You can change the dimensions for the next image you’d like to upload, but how about the previous thumbnail that wordpress has made? That’s the point. This is all about make a custom-size-thumbnail for ALL posts. :)

  9. Dian (1 comments)6 October 09

    I was thinking to create this for my own project,
    but you’ve done it first :) thx!
    Salam kenal ya gan :)

  10. ihasaFLAVOR (3 comments)6 October 09

    Errorhandling please. Wordpress’ errorhandling is alrdy not that great, atleast make sure the additions are fewlprewf

    • I’m sorry but i don’t understand it. Can you give us clearer explanation? :)

    • ihasaFLAVOR (3 comments)8 October 09

      The whole script assumes it will all go well. If theres a malfunction or hickup somewhere (larger uploads timeout for example) the script doesnt check if everything is still ok.
      I dont know if you made this script yourself but its advisable to build in some checks first, or atleast for the next new addition.

    • FYI, i don’t write the script by myself. It’s Darren Hoyt’s. :)

  11. Indrek (2 comments)6 October 09

    I was actually looking for a way of adding automatic thumbnails next to my posts for a site of mine. I’ll try it out later.

    Thanks

  12. Yo (1 comments)6 October 09

    This works, but the markup is ‘invalid’ w3c validator.

    • I know, that’s the problem of using this method. That’s because the ? used in the link. W3C Validator marks it as invalid. However, in my point of view, valid xhtml not everything. I’ve checked several famous sites (including ProBlogDesign) and some of them are invalid in w3c validator. In my opinion, common visitor (which is majority of internet user) will not questioning whether your site is valid xhtml or not (as long as it’s not too much, doesn’t crash with site’s usability and still reasonable).

      However, this method is just an alternative of too-many-things-to-do-in-the-usage-of-custom-field, in my opinion :)

  13. Babak (1 comments)6 October 09

    Dude what are you using for syntax highlighting in the post?

  14. Jermayn (1 comments)7 October 09

    Hi,
    I have a preview plugin installed as well and when using that I managed to get the TimThumb to work fine:
    http://www.kick2kick.net/afl/?.....=new-theme

    But when moved over to the proper site (http://www.kick2kick.net/afl/), it did not work. Any ideas? I did have some trouble with the “What Would Seth Goddin Do” plugin but I disabled that.

    From what I gather its the functions file…

    • Several folks who read this post already use this method and it’s working fine. If the method doesn’t work, there are three suggestion:

      1. There’s something missing when you applied this method. Check again, is there something left?
      2. conflict with another function
      3. (i’m not sure myself, but there’s still a possibility) your server setting is not cache-enable.

  15. Hello Help (2 comments)8 October 09

    Would you recommend this hack over the arthemia template method?
    It utilizes timthumb but this seems to be lighter and does not require the custom field. Will this work if i don’t upload images in wordpress?
    I would like to have an image folder on my server instead of uploading in wordpress.

  16. Andreas (2 comments)8 October 09

    Hi,
    thanks for sharing this!
    Is there a way, to use a “default.jpg” if there isn’t a picture in the article?

    Best regards,
    Andreas

    • I haven’t get any way to do it when i was tweaking this code :P

      But there’s some suggestion in my mind: Tweak its background using CSS so if there’s no image, the CSS background is “no image for this post” image as it background :)

  17. Here is another way to display thumbnails, I dint use the automatic resize script as it will be additional load on server.

    http://swiftthemes.com/2009/10.....ess-theme/

  18. This seems to essentially do the same thing as the_attached_image plugin, as well.

    But it’s great to know another way to accomplish this feature. Thanks!

  19. I agree with your mind, thanks for your methods, I will use this code in my blog.

  20. iain (1 comments)10 October 09

    You saved my life.
    Thank you!

  21. Hey Fikri, we implemented this over at http://OnThisIsland.com but it landed us in two hot pots… Firstly the database was being battered everytime the index page or category pages were loaded. Secondly the single file timpthumb.php was being accessed hundreds of times simultaneously, leading to high loads and complaints from our host.

    To fix this, we simply editted the timpthumb.php file to save the cached thumbnails name as a custom field automatically, and slightly adjusted the code from wprecipe to first check for the cached thumbnail before generating a new one using timthumb.php

    This speeded up the loading of the main pages immensely… for more info check the post here : http://inztinkt.com/blog/2009/.....ur-server/

    Hope this helps :)

    • Very interesting post, will definitely have to take this into account. I haven’t tried out your code, but I’m going to add the link to your post to the end of this one! :)

      Thanks for sharing!

  22. How do I specify a default image or remove the script if there is no image in the post??

    • You could set your tumbnail div a background-image. So if your Post don’t have any images, the background-image of your div will shown.

      How to hide it completly would be interesting.

  23. It seems like there’s always something new being released related to Wordpress, and it’s so great to see so much work being done on a great open-source blogging platform.

  24. Hello Help (2 comments)11 October 09

    Will this only work if you upload an image using wordpress’ add media in the admin panel? Will this work if you add if you add an image src in the post instead?

    • from what i believe timpthumb.php doesnt allow you to create thumbnails for images not hosted on the same server as the file… so only images uploaded through the insert media wordpress system will be cropped and such

  25. I didn’t have time to check thoroughly the TimThumb.php script. Does the script create a thumbnail at first run and then load it from the server? Or does it go through creating a thumbnail from the source image every time? If it is the second case, this plugin, or however you wish to name it, can only be used on small sites. Use it on a large website with lots of visitors, and calling the GD image library functions on each page reload will crash your server in no time.

    Also, what happens when the source image is not directly proportional to the desired thumbnail size? Say thumbnail is 150X150 px, a square, and the source is 400X1200 px.

  26. Is there anyway to do this for other posts other then the one that’s chosen defaultly… like random images or related images type of thing after a post.

  27. Real good tips ! I will probably try it on my new next blog theme, thx !

  28. Nice Post Fikri… this trick has been implemented too by Jauhari on some of Jauhari WordPress Theme such as Vina and I currently modified Ndadap :)

  29. Thanks Fikri! very nice post!

  30. Thanks Fikri! This is just so lovely!! I keep having problem with the excerpt and thumbnail plugin.

    Yours is just so marvelous with the clear guide. I follow only one time and bingo!

    Keep up with the good work!

    You rocks!

  31. Some little tweak for those who like to have a default picture if there isn’t any photo in your post.

    <?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, '’);
    $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],’

  32. Thanks Fikri!

    Great post, I’ve been wanting to get this working for a while now.

  33. It works fine. btw. with Wordpress 2.9 we will get a new Function for Post image (the_post_image)…

  34. Thank you! It works great on my site: http://www.binarynow.com/articles/

  35. zoel (1 comments)19 October 09

    Nice, I used your trick, but default image from post is still showing..how to hide? thanx..

  36. Hi, nice post! I haven’t tried the “tricks” you gave here but we will definitely try them soon. This is helpful to our offshore web development business. Thanks!

  37. Thanks so much! Just so helpful and really clear instructions. I don’t want to rely on plugins for everything or make my clients try and get their heads around custom fields so this is a perfect solution. Now have it working on one of my test sites. Thanks a bunch!

  38. Thank you so much for this! It worked without a hitch on my upcoming theme.

  39. Useful tips. Keep it up. :-)

  40. kevin (19 comments)28 October 09

    Any chance somebody would have found a way to make it work with external pics ? This solution is almost perfect but still missing this.

    • kevin (19 comments)28 October 09

      Dammit am going nuts, works perfectly offline with easyphp but nothing’s appearing online on a test blog, not even the default pic.

      Ho by the way, i added this line:
      else {echo bloginfo(‘template_url’).”/images/padrao_w.png”;}

      just under:
      if(stristr($image[$num],’<img')) { echo $imgThumb; }

      and gives me a default image if not pic is present within the post (but only offline!!).

      Any idea ?

  41. Yoshz (1 comments)29 October 09

    Thanks for this post, it’s help me to create thumb without using custom fields.
    great sharing Fikri

  42. nedir (1 comments)1 November 09

    thanks supper images…

  43. I am very much a newbie compared to your other posters. My theme (from Elegant Themes) already uses timthumb.php so I’ve been doing the custom field approach. I inserted the code into functions.php, but then got a little nervous on implementing the rest.

    Is there a way to do your hack in combination with code that is pulling thumbnails from the custom field. For example, can I add the code to the “if” statement “// if there’s not a thumbnail”? Here’s the thumbnail code currently inside the loop:

    <a href="” rel=”bookmark” title=”Permanent Link to “><img src="/timthumb.php?src=&h=120&w=120&zc=1&q=100″ width=”120px” height=”120px” alt=”" />

    Any advice you have would really be appreciated! I dread going back and adding custom fields to my old posts as it takes away time from adding new content!

    Thanks,
    Melanie

  44. It didn’t print the code correctly for me – another sign I’m a newbie! Here it is again!

    <a href="” rel=”bookmark” title=”Permanent Link to “><img src="/timthumb.php?src=&h=120&w=120&zc=1&q=100″ width=”120px” height=”120px” alt=”" />

  45. That didn’t work either. Can someone email me? I don’t know how to paste the php code in a comments field so all of it appears. Ugggh! :-)

  46. Ste (1 comments)3 November 09

    hi! fantastic guide thx a lot! I was looking this from a long time!
    I have a question… How can i make also for the “screen” otion? I have some screen and I would like to keep it. I tried to change screen with Thumbnail but doesn’t works!

  47. kabir (3 comments)6 November 09

    I don’t know how to Create php file and where to paste in the function Php files. My function php files already have some…..
    ’sidebar1′));
    register_sidebar(array(‘name’=>’sidebar2′));
    ?>
    My question is where I have to paste the source code in the function php files. is it with in the loop or outside the loop.

  48. To display a default image, when there is none attached to the post:

    Simply add the code bellow BEFORE $more = 0;

    else {echo “wp-content/themes/YourTheme/img/default-image.png”;}

  49. @Fikri – Thank you so much for this great solution! It worked perfectly, and it allowed me to streamline on the number of plugins. The other really good part, is that it generated thumbnails on the fly that I did not create previously, because I turned that off in WP. We’ll see how the new WP 2.9 feature will compare to this.

    @Angelica – very cool, thanks!!

  50. when you say copy to your theme folder, is it means copy to the root of theme folder or copy to the folder of the specific themes

    regards

  51. Very helpful! I’m using a theme that already has TimThumb integrated so I’m good to go!

  52. I’m developing a site where this script was very useful. However I’m not going to be managing it and know the site’s owners won’t be posting images with each new post, nor would want a default image to appear instead.

    For those who are in the same situation I’d like to share my fix:

    post_content;
    $searchimages = ‘~]* />~’;

    /*Run preg_match_all to grab all the images and save the results in $pics*/

    preg_match_all( $searchimages, $content, $pics );

    // Check to see if we have at least 1 image
    $iNumberOfPics = count($pics[0]);

    if ( $iNumberOfPics > 0 ) { ?>

    <img class="thumbnail" src="/timthumb.php?src=&w=150&h=150&zc=1″>

    Hope this helps anyone.

  53. Code got cut off. Here’s the rest:

  54. or not… Well, you get the idea if you know any code. The first part is the key and then just echo the excerpt in the else statement.

  55. Lovely post! helped me lot ! thanks

  56. Jean (2 comments)25 November 09

    Is there a way to prevent wordpress from automatically displaying thumbnails of any images inserted into the post before the tag?

  57. kevin (19 comments)30 November 09

    Is there a chance that the function getImage() could return the height of the pic ? Am no php developper but i’d need this function. Thanks.

  58. Jean (2 comments)30 November 09

    Been expanding on this, check out my post here
    http://www.jeangalea.com/wordp.....nail-hack/

  59. Love it Fikri!

  60. Thanks for the code… i ll add the code and remove the plugins

  61. Hi

    I kinda like this code. But there is one problem with my website. Many of my post does not have “image” in it. They are just pure text.

    I used this code and it show broken image link. Is there anyway to work around to get “default” image to show up when there was not any image in the post

    thanks,
    Komgrit

  62. Artur (1 comments)14 December 09

    Thanks for nice tutorial! I was wondering if there’s any way to grab first image from post’s gallery instead of any first image in post. (Hope you get what I mean ;) ).

  63. raj (2 comments)15 December 09

    Hey Fikri Rasyid !

    Thanks for ur simple functions..it saves my time ….

    I have two doubt…
    1.can i show the default image,if the post dont have image.
    2.how to get the images from my subdomain.
    for ex: (http://media.domainname.com)

    i had used your method it works fine..when i have changed the misc path to subdomain in wordpress.timthumb does’t fetch..

    pls reply me..

    ThannQ

  64. Alps (1 comments)20 December 09

    This could be perfect if there is way to show a default image if no image has been detected by the script! Will check soon for updates! :D

  65. This is a really nice post. In Wordpress 2.9 there is a new way to do it that is really simple and requires much less code.

  66. Ezequiel (2 comments)15 January 10

    Hello, thats is nice but don´t work for me :( i place the code in index.php but dont work. please help

  67. Ezequiel (2 comments)15 January 10

    i use wordpress 2.9

  68. andrea (2 comments)18 January 10

    Grazie Mille!!!

  69. Haryo (2 comments)23 January 10

    Although Wordpress 2.9.1 have new feature to do it simple, your post gimme some new ideas. thanks

  70. JC (4 comments)24 January 10

    This is great information. The problem I’m having is that I’m getting two images on the front page of my blog: one is the auto-resized TimThumb image (which is awesome) and the second is the image I inserted into my post.

    How do I hide this second image on the home page (so only the TimThumb shows) and keep the image in the single post view?

  71. Cosmin (1 comments)29 January 10

    Although this approach has been phased by WP 2.9’s thumbnail capability, we can still take something home from that PHP code.

    Thanks for taking the time to write it :)

  72. Haryo (2 comments)2 February 10

    I’ve tried to compare these tips with “Get The Image” Plugin on WP 2.91. I think this tips running better than than using that plugin. Great Job bro!

  73. Ellen (1 comments)6 February 10

    Thanks for this grat tip, I just tried it out and it workes great :-)

  74. thanks bro,
    I must upload a picture to show a thumbnail, more works and more space in my site. May this help me. But I must do some modification in my current theme.

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?