Fetch the first image from the post

Apr 26, 2013 | Blog |

We can grab the first image from the post content using the below function.

function fetch_first_image($id) {

$p = get_post($id);

$first_img = '';



$output = preg_match_all('//i', $p->post_content, $matches);

$first_img = $matches [1] [0];


$first_img = "/images/default.jpg";


return $first_img;


Under template use the function like below

ID); ?>

or in loop

Use this code in functions.php of theme and makes sure you have a default image in images folder. So if no image found default image will show up. You can ignore default image if not required.