[wp-hackers] Extract first image from a post

Alex Hempton-Smith hempsworth at googlemail.com
Sun Nov 23 22:29:39 GMT 2008


Okay, after some searching I've managed to get it working with some very
complicated (for me anyway) code, it goes completely over my head but at
least it works!
For anybody who's interested:

function teaserimg()
{

   ob_start();

       the_content();

       $html = ob_get_contents();

   ob_end_clean();
   $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $html,
$matches, PREG_SET_ORDER);

   $p = $matches [0] [1];

   // maximum width is defined here
   $mw = '215';

   // maximum height is defined here
   $mh = '160';

   if(list($w,$h) = @getimagesize($p)) {
   foreach(array('w','h') as $v) { $m = "m{$v}";
       if(${$v} > ${$m} && ${$m}) { $o = ($v == 'w') ? 'h' : 'w';
       $r = ${$m} / ${$v}; ${$v} = ${$m}; ${$o} = ceil(${$o} * $r); } }
   return("<img src='{$p}' alt=' ' width='{$w}' height='{$h}' />"); }
}

-- Alex


More information about the wp-hackers mailing list