Grab first image from a WordPress post

Wordpress First Post Image codeEver wanted to use the first image in your post as a teaser for your blog listing just like on the Michon International Blog here’s how we did it.

Place this piece of code in your themes function.php

function first_post_image($content) {
   $first_img = ”;
   $output = preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, $content, $matches);
   $first_img = $matches [1] [0];
   return $first_img;
}

Then use it in the post loop as follows.

<? php echo first_post_image(get_the_content()); ?>

You need to pass it the content of the post, as it searches the post HTML for the first img tag and extracts the src url. So use “get_the_content()” instead of “the_content()” which returns the content as a string.

 

You can also use a empty test to check if there is an image with the post and style the post accordingly

<? php $first_img=first_post_image(get_the_content()); ?>

 <?php if (!empty($first_img)) { ?>
            <div class=”mobile-box-img”>
                  <a href=”<?php the_permalink() ?>”>
                     <img class=”alignnone” title=”<?php the_title(); ?>” src=”<?php echo $first_img ?>” alt=”<?php the_title(); ?>” width=”170″ />
                  </a>
            </div>
<?php } ?>

Submit a Comment

Your email address will not be published. Required fields are marked *