Automattic WordPress Post Thumbnails

There are plenty of posts floating around the internet about using Custom Fields to assign thumbnail images to individual posts in WordPress. Web Developer Plus has a different idea.

Do you often put images in your posts? You probably upload them through the media manager built right in to the WordPress post editor. Every time you upload an image, it’s associated with the post you first attach it to. And WordPress creates a thumbnail to go along with it, of the size specified in the media settings.

Web Developer Plus has a an article on how to automatically find the thumbnail URL of the first image attached to a post and store it in the variable $img, which you can then echo out into an <img /> tag wherever you want the thumbnail to appear.

//Get images attached to the post
$args = array(
 'post_type' => 'attachment',
 'post_mime_type' => 'image',
 'numberposts' => -1,
 'order' => 'ASC',
 'post_status' => null,
 'post_parent' => $post->ID
$attachments = get_posts($args);
if ($attachments) {
 foreach ($attachments as $attachment) {
 $img = wp_get_attachment_thumb_url( $attachment->ID );
<img src="<?php echo $img; ?>" alt="Post Thumbnail" />

That’s a bit easier to handle, isn’t it? Once you have it set up, you don’t have to mess around with custom fields whenever you write a new post.

How To Use Thumbnails Generated By WordPress In Your Theme [Web Developer Plus]

  • Dean Saliba

    This is a great idea. I'm going to test this out on one of my blogs some time today.

    Cheers for sharing it. :)

  • Ed Nailor

    This is EXACTLY what I was seeking! I was using the Thumbnails for Excerpts plugin, but the thumbnails would get really ugly at times.

    One addition I made that might help othere…
    1. I added <code>$img=null</code> at the start of the code so I could use this in a list of posts
    2. I added a default thumbnail if there wasn't one. Added following to end of code:
    <code>if($img=='') echo('<img src="/PATH/TO/IMAGES/default-thumb.jpg" alt="Read entire article" class="img_thumb" />'); else echo('<img src="'.$img.'" alt="Read entire article" class="img_thumb" />');</code>

  • Mansur

    so many tutorial I follow… nothing resulting success..

    until I read this post.. just copy and paste, make the magic…

    TQ for this post i really aprreciate it….