Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This question already has an answer here:

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>' ) ); ?>
        </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?

share|improve this question
add comment

marked as duplicate by Tom J Nowell, s_ha_dum, brasofilo, Johannes Pille, kaiser Mar 27 '13 at 14:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer

up vote 1 down vote accepted

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

<?php 
// 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 = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  //Defines a default image
  if(empty($first_img)){ 
    $first_img = "/images/default.jpg";
  }
  return $first_img;
} 

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

share|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
add comment

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