Here you have a function which gets you the first image from a wordpress post. The whole point of this piece of code is to make it easier for people to retrieve images from their posts. If you want to pull the first image of a post then this is the code you need. Simply put this into your functions.php and echo the result of this function inside the loop.

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;
}
This entry was posted in Do it yourself, Tutorials and tagged , , , . Bookmark the permalink.

Leave a Reply