How to retrieve an image from a post and display it before excerpt of a post? [duplicate]

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?

1 Answer
1

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(); ?>

Leave a Comment