Because instinct alone wouldn't be distinctive enough.
The Personal Ramblings of Hector Kolonas.

Getting First Image from Wordpress Post, Without Killing Your Server
Sunday May 03rd 2009, 5:59 am
Filed under: Opinion

OK, so over at OnThisIsland we had a problem arise from the fact that our first-image-fetching function was killing our server. We had warnings flying in from our hosting company, and pages slowing down to unbelievable speeds. After a bit of investigation we realised that on each archive, home or search page, this function was called about 10 times, making it search through 10 different articles to find the image EACH time it loaded.

What we did was make it store a custom field automatically on its first load. (We also made it return a default image as we were using timthumb.php to resize images on the fly and didnt want to resize externally hosted images).

Here’s my version to get the first image from an article. Its partially based on the Wordpress Recipe and some ideas of my own. Hope you find it useful.

<?php
function getImage($post){
$externalimage = get_post_meta($post->ID, ‘external’, true);
$gthumb = get_post_meta($post->ID, ‘gthumb’, true);
if ($externalimage==”TRUE”){
$returnimg = “http://www.yoursite.com/default.png”;
} else {
if ($gthumb==”"){
$szPostContent = $post->post_content;
$szSearchPattern = ‘~<img [^\>]*\ />~’;

// Run preg_match_all to grab all the images
//  and save the results in $aPics
preg_match_all( $szSearchPattern, $szPostContent, $aPics );

// Check to see if we have at least 1 image
$iNumberOfPics = count($aPics[0]);

if ( $iNumberOfPics > 0 ) {
for ( $i=0; $i < 1; $i++ ) {
$img = explode(“\”", $aPics[0][$i]);
$returnimg =  $img[5];
//    ==> Added to combat server performance.
add_post_meta($post->ID, ‘gthumb’, $returnimg, true);

};//end for
};//end if no. of pics more than zero
} else {
$returnimg =  $gthumb;
}; // end if gthumb is set
}; //end of if externalimage
return $returnimg;
}//end function getImage

?>


No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)