thumbnail-size
featured, tech

Automatically display images in WordPress themes

Want to automatically display an image for each post in your custom WordPress theme without resorting to custom fields or asking the writer to jump through any hoops? How about displaying one size on the home page and another for the “single” pages?

One thing I’ve wanted to do a few times when designing WordPress themes is to automatically display an image for each post (if one has been uploaded). As far as I know, WordPress doesn’t currently have a convenient way of doing this built-in, but it’s quite easy to write the function into your custom theme.

First, you need to configure the WordPress settings to choose the size of your thumbnails. For this example, I set the small thumbnail to 64 x 64 pixels and clicked the crop option.

Inside the post loop, simply insert this code. It’ll grab the first image listed in the database associated with the current post. Then, in this case it looks for the thumbnail that’s been automatically sized to 64×64 pixels and stores the results in the variable $image for automatic use in your theme.


$image = "";
$post_attachments = $wpdb->get_results("SELECT guid "
."FROM $wpdb->posts "
."WHERE post_parent = '$post->ID' "
."AND post_type = 'attachment' "
."ORDER BY `post_date` ASC "
."LIMIT 0,1"
);

if ($post_attachments) {
$image = $post_attachments[0]->guid;
$image = str_replace(".jpg","-64x64.jpg",$image);
$image = str_replace(".png","-64x64.png",$image);
$image = str_replace(".gif","-64x64.gif",$image);
}
?>
# Do something with the $image

Say, however you’d rather load your medium sized image automatically. First, set your thumbnail size to your preferred dimensions.

Then the code is slightly trickier since we can’t infer the exact filename by knowing the thumbnail size since only one dimension is going to match. So, we build the filename with what we know, and then use the glob command to list the filename that matches:


$image = "";
$post_attachments = $wpdb->get_results("SELECT guid "
."FROM $wpdb->posts "
."WHERE post_parent = '$post->ID' "
."AND post_type = 'attachment' "
."ORDER BY `post_date` ASC "
."LIMIT 0,1" );

if ($post_attachments) {
$sourceimage = $post_attachments[0]->guid;
# pick up the image with size 470 if one exists
$sourceimage = str_replace(".jpg","",$sourceimage);
$sourceimage = str_replace(".png","",$sourceimage);
$sourceimage = str_replace(".gif","",$sourceimage);
$root = $_SERVER['DOCUMENT_ROOT'];
foreach (glob("$root$sourceimage-*470*") as $filename) {
$image = $filename;
$image = str_replace("$root","",$image);
}
}
?>

This method is a fairly user friendly, allow you to wrap your images in links or other formatting commands in your theme without burdening your users with manually entering code every time. I also found the Regenerate Thumbnails plugin useful when retro-fitting old sites with this upgrade.

I’d love to hear your thoughts or if you find it useful for your theme.

Standard