Get the first image from the post and display it in WordPress

By default, WordPress will not take your images with the excerpt on the homepage. This is the reason why many people use the thumbnail function or custom fields to display an image for the article on the front page.

However, there is a simple way to display the first image of your article on the front page with a function.

For that, just add this code to the functions.php theme file

function catch_that_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];

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

Then you can call this function from within the loop

<?php echo catch_that_image() ?>

mirkohumbert

Comments

No comments yet.

Write a comment

You must be logged in to write a comment.

« »