I have a site that needs to display the first image from any given post in a specific category. I have it working, and have added code below. My question is, is there a better way? This seems awfully kludgy.
I’m parsing the post data for whatever first appears between src="
and "
. Any gotcha’s that i’m missing? Does WordPress have a better way to do this built in?
function extractStringFromString($string, $start, $end) {
//Finds the first string between $start and $end.
$startPos = strpos($string,$start);
$stringEndTagPos = strpos($string,$end,$startPos);
$stringBetween = substr($string,$startPos+strlen($start),$stringEndTagPos-$startPos-strlen($start));
if (strlen($stringBetween) != 0 && $startPos!= '') {
return $stringBetween;
}
else {
return false;
}
}
function getfirstimage($post){
//Returns url of first image located in post data
global $wpdb;
$sqlquery = "SELECT post_content FROM `wp_posts` WHERE `ID` = $post LIMIT 0 , 1";
$result = $wpdb->get_results( $sqlquery );
$result = $result[0];
$postcontent = $result->post_content;
if ($result){
return extractStringFromString($postcontent, 'src="', '" ');
}
else return 0;
}
3rd Option: Use a Dom Parser
This should get you started in the right direction. Regular Expressions won’t account for malformed HTML, and not all Images in your Post HTML are necessarily attachments.
Use this, and replace the $post->ID probably with get_the_ID() if you are inside The Loop.
Source: WordPress Support Forums
There’s a very nice plugin called Get The Image. http://wordpress.org/extend/plugins/get-the-image/
Call by
<?php if ( function_exists( 'get_the_image' ) ) get_the_image(); ?>
The function: