Since we have been having trouble with the image resizer the Gazette theme, I'm wondering if anyone has had any success with a thumbnail plugin or anything like that. We'd like some images to be shown next to our search results and also in our RSS feeds.
Here's a code snippet you could use. It's not perfect nor pretty but works (though, it could use some error checking and less hooking into admin functions and less usage of ABSPATH). Add to functions.php.
/* * Returns the first image attached to a post * @param $size One of 'thumbnail', 'medium', 'large', 'full', or array( width, height ) * @param $crop Crop the image if true */ function get_first_image( $size='thumbnail', $crop = false ) { global $post;
if($crop) { // Include WordPress Image functions | needed to resize require_once(ABSPATH.'/wp-admin/includes/image.php');
// Get the path for the image $img_path = get_attached_file($attachment_ID); // Crop & Resize the image $cropped = image_resize( $img_path, $size[0], $size[1], true);
// Get the new image URL $attachment_url = wp_get_attachment_url($attachment_ID); $img = path_join(dirname($attachment_url), basename($cropped)); } else { //We're not cropping, so we just get the image src directly $img = wp_get_attachment_image_src($attachment_ID, $size); $img = $img[0]; } return $img; } return null; }
If you don't care much about the ability to get custom sizes or crop images:
/* * Returns the first image attached to a post * @param $size One of 'thumbnail', 'medium', 'large', 'full', or array( width, height ) */ function get_first_image( $size='thumbnail' ) { global $post;
Ah, yeah, good point Will. This wouldn't work for images linked from other websites. Wouldn't work either if you reuse an image across multiple posts (though, the simple workaround for this is to re-upload the image for each post — but that has obvious disadvantages).