WebDev
Category: Wordpress
Get the First Image from a Post in WordPress
Posted on September 28, 2010, at 3:57 pm

Here’s a quick way to pull the first image from a post using WordPress. In your functions.php file, put the following:

function getfirstimage() {
  global $post, $posts;
  $iimage = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $iimage = $matches[1][0];
  if(empty($iimage)){ //set a default image if post has no image
    $iimage = "/images/default.jpg";
  }
  return $iimage;
}

If you call getfirstimage(); from within your loop, it should give you back the first image (if there is one).

The gibberish you see inside of the preg_match_all function is known as Regular Expressions. It is quite widely regarded as a mini coding language all its own. I found a limitation in the example shown above, which I use in my “On the Go” latest post in my sidebar. It seems, if there are multiple tags beside each other (like multiple pictures) with no spaces or other any other characters in between, the regular expression will keep searching until it finds the very last closing tag before a breaking character or the end of the post. Any suggestions for a fix?

More Updates...
  • Postnatal care in France. Interesting!
  • The Snuggle Sutra For Valentine’s day.
  • Movie Posters re-imagined in another time.
  • Pepper's too pushy! Nominating a new consort for Salt…
  • Was Marilyn Monroe fat? Simon Doonan reveals what he discovered when rifling through the icon’s belongings.
  • Bill Hicks would have turned 50 recently.
  • Ross Douthat, Gravedigger
  • Slate's Announcement of Christopher Hitchens’ passing.
  • See more...
    Blair Kelly
    I'm a skeptic, freethinker, and secular humanist.

    After a year as a content developer at a successful IT company, I'm taking some time to regroup and set a new course.

    I hold a combined honours degree in communications studies and multimedia from McMaster University.