WordPress

First content image as Featured Image on listing page

This code will display the first content image as the featured image on the listing or archive page.

Add the below code to the functions.php file

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

  if(empty($first_img)) {
    $first_img = "/path/to/default.png";
  }
  return $first_img;
}

To implement the code above use the code below

<img src="<?php echo content_first_image(); ?>" alt="<?php the_title(); ?>">