Find the first image in a WordPress post

There are some snippets of code that stand you in very good stead, and this one, to find and display the first image in a post, is one such. I wrote it for Dan's blog nearly a year ago, and have used it so many times since, most recently just yesterday for Taexalia's new blog theme.

If you have a magazine-style theme, wanting to find the first image in a post and display it on your home page along with an extract from the post is pretty common. There are a few ways to do it: you can use PHP's regex functions, but frankly for this, they're memory-hogging overkill, and it's better to use a simpler way if there is one. This is what I do:

This bit goes in functions.php:

function bm_extract_string($start, $end, $original) {
$original = stristr($original, $start);
$trimmed = stristr($original, $end);
return substr($original, strlen($start), -strlen($trimmed));
}

and this goes in index.php or whereever you want the picture to appear (it needs to be within a loop):

<?
$content = get_the_content();
$pic_string = bm_extract_string('src="','" ',$content);
echo '<img src="'.$pic_string.'" />';
?>

For those who want to know how it works: the second bit of code takes the post content and extracts the bit between the first occurance of src=" and the next of " plus space - in other words, the filename of the first image in the post content.

If you know any PHP, you'll probably spot that the fuction can be used to extract any substring: I've yet to use it with WordPress for anything else, but if you wanted to find the first link in a post, say, you could use it for that by changing the second bit of code to

<?
$content = get_the_content();
$link_string = bm_extract_string('href="','">',$content); //this may need tweaking if your links use CSS classes
echo $link_string; //or whatever you want to do with the link
?>

Share this post:
  • email
  • del.icio.us
  • Facebook
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Tumblr
  • Twitter

Tags: ,

Posted by Sue on June 7, 2009 in Themes, WordPress.

17 comments to "Find the first image in a WordPress post"

  1. Josdigital wrote:

    great, thanks for that.
    i've found another solution here, using regular expressions, but yours will probably be faster. Am I right?
    http://wordpress.org/support/topic/246893

  2. Arch1k wrote:

    [Edit by Sue: code below not tested by or supported by me]
    Hello,
    I made a small variation to your (awesome/lifesaver) script so that it would embed the original width and height of the image, which were crucial for my portfolio gallery.
    Here goes:

    Functions.php
    // Retrieve the src pf first image in a post
    function bm_extract_string($start, $end, $original) {
    $original = stristr($original, $start);
    $trimmed = stristr($original, $end);
    return substr($original, strlen($start), -strlen($trimmed));
    }
    function getFirstImage() {
    $content = get_the_content(); $pic_string = bm_extract_string('src="','" ',$content);
    $imagesize = getimagesize($pic_string);
    list($width, $height, $type, $attr) = getimagesize($pic_string);
    echo '';
    }

    index.php

  3. Arch1k wrote:

    [?php getFirstImage(); ?]

    • Arch1k wrote:

      [Edit by Sue: code below not tested by or supported by me]

      Sorry for all this mess. Hope this one turns out right:
      Functions.php hase this:
      // Retrieve the src pf first image in a post
      function bm_extract_string($start, $end, $original) {
      $original = stristr($original, $start);
      $trimmed = stristr($original, $end);
      return substr($original, strlen($start), -strlen($trimmed));
      }
      function getFirstImage() {
      $content = get_the_content(); $pic_string = bm_extract_string(’src=”‘,’” ‘,$content);
      $imagesize = getimagesize($pic_string);
      list($width, $height, $type, $attr) = getimagesize($pic_string);
      echo '< a href="'.$link.'" style="background:url('.$pic_string.'); display:block; width:'.$width.'px; height:'.$height.'px;"></a> ‘;
      }

      and inside your index.php simply put this:
      <?php getFirstImage(); ?>

  4. Mark wrote:

    [Edit by Sue: code below not tested by or supported by me]
    I added a "no image found" function:

    $content = get_the_content();
    $pic_string = bm_extract_string('src="','" ',$content);
    if ( $pic_string == NULL ) {
    echo '';
    } else {
    echo '';
    }

    Edit: I can't get the code to show up correctly.
    It searches for the first image, if it is not there it inserts a path to a generic image

  5. Sue (@blogmum) wrote:

    Thanks Mark!
    Memo to self: fix comments so people can post code...

  6. Jzatt wrote:

    Awesome! This was just what I was looking for. Have been searching for a way to extract the first link for a while, this works just the way I want it! Thanks alot, really saved my day!

  7. andrea wrote:

    Hello, I need exactly what Arch1k wrote about, a code that embed the original width and height of the image. But the code posted don't work. When I add the code in the functions.php and save the page returns a blank page and the entire blog stops working. Any help to make the code of Arch1k work correctly? Thanks

    • Sue wrote:

      If you use the getimagesize() PHP function, Andrea, you should be able to do whatever you like.

      • andrea wrote:

        Thanks for fast reply Sue, problem is that I don't know how to write in PHP so I cannot make the code by myself. If you or someone here know where I can find a similar code that works will be great...

  8. Ceys wrote:

    Hiya, this looks really excellent, but I had a question (I'm learning php slooowly):

    Is there a way where if there is no image present you can automatically substitute with a default image?

    I'd like to use it on my photography blog once I redesign it and start posting again, but I very occasionally post without photos and it'd be good to have something there to keep it looking consistent!

    Thank you :)
    Cerys

Tweetbacks

  1. RT @Biddy Blog Mum post: http://blogmum.com/?p=722 Find the first image in a WordPress post

Leave a Reply