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

  // Defines a default image here
    $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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.