Get the first image from the wordpress post and display it

An easy function to get the first image from a post.

The Code

<?php
function get_first_image() {
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;
}
?>
<?php
echo get_first_image();
?>

via

Tags: ,


  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • LinkArena
  • LinkedIn
  • MisterWong.DE
  • Reddit
  • Technorati
  • Tumblr
  • Webnews.de
  • Add to favorites
  • Yigg
  • email
  • Print
  • RSS

  1. Toure on Tuesday 21, 2009

    Hello, thanks for the code.
    However, I have used your code without success. It’s outputting the url of the image instead of the picture itself.

  2. Alexander on Tuesday 21, 2009

    put the url in an image tag



Switch to our mobile site