Return to Snippet

Revision: 20916
at December 1, 2009 05:35 by LuckyShot


Initial Code
// Get URL of first image in a post
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}

// With TimThumb
<img src="/thumb.php?src=<?php echo catch_that_image() ?>&w=200&zc=1&q=200" alt="<?php the_title(); ?>"/>

Initial URL
http://wordpress.org/support/topic/246893

Initial Description
To call it just put <?php> in your template file within the loop.

Initial Title
Wordpress - Get first image of post (without Custom Fields)

Initial Tags
image, wordpress

Initial Language
PHP