I'm customizing a WordPress template and I would implement the following behavior in the excerpt posts visualization in my homepage:

If a post contains images (one or more), in the homepage post preview show at the begining a thumbnail of the first image that is in the post, then show the excerpt of the post.

At the moment I have the following code that, inside a WordPress loop, show the excerpts of all posts in homepage:

<!-- .entry-summary -->
        <?php else : ?>
        <div class="entry-content">
            <?php the_excerpt(); ?>
            <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'admired' ) . '</span>', 'after' => '</div>' ) ); ?>

As you can see this code snippet show the excerpt of a post.

Is it possible to find the first image in the post, put it into a variable and show it inside a span (or some other HTML tag) before the excerpt visualization?


if it is the "Featured Image" of your post, you can use:

// check if the post has a Post Thumbnail assigned to it.
if ( has_post_thumbnail() ) { the_post_thumbnail(); } 

check: the_post_thumbnail function

else if you want to get the first image inside your post, you can use somthing like that:

function get_first_post_image() {
  global $post, $posts;
  $first_img = '';
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  //Defines a default image
    $first_img = "/images/default.jpg";
  return $first_img;

Then place <?php echo get_first_post_image(); ?>

| improve this answer | |
  • ok, maybe I am loosing something. From what I understand I can use the "Featured Image" of my post without using extra function...but what is it this "Featured Image"? how can I set it in my posts? – AndreaNobili Mar 27 '13 at 14:10
  • ok, solved: the I can set the "Featured Image" when I create or I modify an article !!! Perfetct !!!TNX – AndreaNobili Mar 27 '13 at 14:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.