Reputation: 51
I need to extract the first image from a post, I found this code but this shows the last image from posts instead (example: http://zonadictoz.com.ar), I don't Know why!
function myPostImage()
{
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
Any ideas?
Upvotes: 0
Views: 178
Reputation: 51
I achieved adapt the code abobe but it seems that is still picking up from the last image, and not the first, how I can reverse it?
Upvotes: 0
Reputation: 4976
Using the features image field is a much more robust solution, but with regards to your code you could change preg_match_all() with preg_match() to make sure only the first match is captured:
<?php
$match = preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if ( $match )
$first_img = $matches[1];
?>
Upvotes: 2