// you’re reading...

Featured

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.

<?php # get the thumbnail image if one exists
  $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);
  }
?>

<?php if ( $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:

<?php # get the thumbnail image if one exists                              
  $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.

Discussion

7 comments for “Automatically display images in Wordpress themes”

  1. Thanks for the article. I was looking to learn how to do this exact thing and found this with google. I will give it a try tomorrow. Thanks.

    Posted by Susan | October 16, 2008, 6:34 pm
  2. I’ll be interested to hear how it works for you. Good luck!

    Posted by Rob | October 16, 2008, 9:41 pm
  3. [...] This retrieves the first 15 posts in category 5. To retrieve the image, I used a custom SQL query (thanks to 185vfx). [...]

    Posted by Image Resizing With WordPress - In the Woods | November 11, 2008, 8:54 am
  4. Perfect! Its work like a charm. Thanks for hack.

    Posted by Akip | December 4, 2008, 2:35 am
  5. Thanks for the article.

    I’m trying to use this technique with the SEO Siloing plugin to draw my posts onto the page with thumbnails. I’m having trouble merging the two and would REALLY appreciate any help.

    Posted by Travis | December 17, 2008, 2:43 pm
  6. @Travis: Unfortunately, I’m not too familiar with that plugin. Maybe the plugin author would want to add this feature for you? I’m considering packaging this little hack up as a plugin myself, but haven’t gotten around to it yet.

    Posted by Rob | December 21, 2008, 8:55 am
  7. Thanks for a great idea. I’ve been tweaking this for my purposes, and now have this function (I hope the code tag works here!):

    function getThumbnail( $postID, $size = "thumbnail" ) {
        global $wpdb;
        $image = "";
        $maxWidth = get_option( $size.'_size_w' );
        $post_attachments = $wpdb->get_results( "
            SELECT  guid
            FROM        $wpdb->posts
            WHERE       post_parent = $postID
            AND     post_type   = 'attachment'
            ORDER BY    post_date ASC
            LIMIT       0,1
        " );
        if ( $post_attachments ) {
            $sourceimage = $post_attachments[0]->guid;
            $sourceimage = str_replace( ".jpg", "", $sourceimage );
            $sourceimage = str_replace( ".png", "", $sourceimage );
            $sourceimage = str_replace( ".gif", "", $sourceimage );
            $sourceimage = str_replace( get_bloginfo( "siteurl" ), "", $sourceimage );
            $root = $_SERVER[ 'DOCUMENT_ROOT' ];
            foreach ( glob( "$root$sourceimage-*$maxWidth*" ) as $filename ) {
                $image = $filename;
                $image = str_replace( $root, "", $image );
            }
        }
        return $image;
    }

    It defaults to getting the thumbnail, or you can ask it to get the medium size, too. It dynamically gets the WP option for the relevant max width and matches on that.

    This function works for my current set up - both thumbnail is set to 80 x 80 and medium is set to 150 x 150. The match allows the max width value found to be anywhere in the filename, i.e. it could end up matching the height of a thumbnail, if you have thumbnail at 80 x 150 and medium as 150 x 300, say. Not sure - please test for yourself before using, but hopefully this idea is of use to someone…

    Posted by Steve Taylor | January 2, 2009, 12:45 pm

Post a comment