Display the post image with your posts excerpts

You spent hours looking for that image that perfectly illustrates your post, but on the main blog page you only display the excerpt. All that work and the impact of the image is lost because the image is only displayed when the reader is viewing the full post.

You can add this function to your theme functions.php to display the thumbnail image of your post or a default image if the post does not have one.

function postimage($width,$height, $text, $class) {
$scriptpath = get_stylesheet_directory_uri();
$attachments = get_children(array(‘post_parent’ => get_the_ID(), ‘post_type’ => ‘attachment’, ‘post_mime_type’ => ‘image’, ‘orderby’ => ‘menu_order’));
if (!is_array($attachments)) {
$image = $scriptpath.”/images/default.jpg”;
echo ‘<img class=”‘.$class.'” title=”‘.$text.'” src=”‘.$scriptpath.’/scripts/timthumb.php?w=’.$width.’&h=’.$height.’&zc=1&q=100&src=’.$image.'” alt=”‘.$text.'” width=”‘.$width.'” height=”‘.$height.'” class=”‘.$class.'” />';
} else {
$img = array_shift($attachments);
$imagelink = wp_get_attachment_image_src($img->ID,’full’);
$image = $imagelink[0];
echo ‘<img class=”‘.$class.'” title=”‘.$text.'” src=”‘.$scriptpath.’/scripts/timthumb.php?w=’.$width.’&h=’.$height.’&zc=1&q=100&src=’.$image.'” alt=”‘.$text.'” width=”‘.$width.'” height=”‘.$height.'” class=”‘.$class.'” />';
}
}

How to use it:
In your template add the function before the call to the_excerpt.

<? postimage(100,75,”image for: “.get_the_title(),’image’)?>
<? the_excerpt(); ?>

The parameters are:
$width & $height – the purpose of these is obvious
“image for: “.get_the_title() – This will become the title and alt text of the image in the tag
image – this is the class for the tag, with this you can align/float the image to the left/right or apply any style you already defined for the images

This function uses the timthumb script to resize and crop the image automatically. after downloading the script, create a subdirectoy named ‘scripts’ in your theme directory and copy the timthumb.php file to it. Now create a ‘cache’ subdirectory in your theme directory and assign it write permissions, so the script can create the images in that directory and skip the creation of the image on every page request.

If your post does not have an image, the function will display a default image. to define the default image upload the image you want to be used by default to your theme in the images directory and name it ‘default.jpg’

Comments are closed.