[wp-hackers] Extract first image from a post

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


In the following code, the script resizes the image proportionally depending
on the width AND the height of the image. That means that if the image is
too wide or too high it will be resized. It just means that a really wide
image can't get through just because it's height was an acceptable height.
Note that it isn't distorted, the proportions are kept the same.

function teaserimg($mw=215,$mh=160)
{

global $post;
$html = $post->post_content;
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $html,
$matches, PREG_SET_ORDER);
$p = $matches [0] [1];
 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}' />"); }
}

You can override the default maxwidth/maxheight settings when you insert the
template tag, for example this would make sure images are resized if they
are higher OR wider than 100:

<?php echo teaserimg(100,200); ?>

-- Alex


More information about the wp-hackers mailing list