How to Get First Image URL from the Post on WordPress

The following function is used to get first image URL from WordPress post.

Paste below function on /wp-includes/functions.php file.

function get_first_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 here
  if(empty($first_img)){
    $first_img = "/images/default.jpg";
  }
  return $first_img;
}

Now you can show the image using this syntax:


<img src="<?php echo get_first_image(); ?>" />

Leave a Reply

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