[wp-hackers] Extract first image from a post
andré renaut
andre.renaut at gmail.com
Sun Nov 23 14:11:07 GMT 2008
I am using this php code to retrieve the first image of a post :
function teaserimg($hmax=100)
{
$teaserimg = '';
ob_start();
the_content();
$html = ob_get_contents();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $html,
$matches, PREG_SET_ORDER);
if (isset($matches [0] [1]))
{
$hw = getimagesize($matches [0] [1]);
if ($hw [1] < $hmax)
{
$hwi = $hw [3];
}
else
{
$h = $hmax;
$w = round ( (($hw [0] * $hmax) / $hw [1]) );
$hwi = 'width="';
$hwi .= $w;
$hwi .= '" height="';
$hwi .= $h;
$hwi .= '"';
}
$align ='left';
$rand = mt_rand (0,1);
if ($rand == 1) $align='right';
$align ='right';
$teaserimg = '<img src="' . $matches [0] [1] . '" alt=" " align="' .
$align . '" border="0" hspace="5" vspace="5" ' . $hwi . '/>';
}
return $teaserimg;
}
More information about the wp-hackers
mailing list