Images in Blog List

Hey I got the code to get the first image from the content, from this answer, Get first image in a post from Diana but modified the code a bit. So if this is helpful please mark that answer aswell.

Insert the code inside your functions.php or create a new plugin.

function catch_that_image() {

global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();

  // search for <img> elements inside the post content
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);

  // $matches now contains an multidimensional array with all found <img> objects
  // we go down the multiarray to find your image URL
  $first_img = $matches [1] [0];

  // check if there is an image
  if(empty($first_img)){ 
    // if no image is found in the content, we can add a default one
    // if you dont want to use a default than just use '';
    $first_img = '/images/default.jpg';
  } else {
    // is an image is found, create some markup and display it
    $first_img = '<img class="my-custom-post-image" src="'.$first_img.'">';
  }

  return $first_img;
}

Than you need to modify your content.php template in your theme folder. (please use a child theme!)

On the top of the template file, you will also see that if you used featured image, this image would already show! And you would not have to do all this here 🙂

So add some changes:

<?php
/**
 * The default template for displaying content
 *
 * Used for both single and index/archive/search.
 *
 * @package WordPress
 * @subpackage Twenty_Fifteen
 * @since Twenty Fifteen 1.0
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <?php

        // new code starts
        if (!is_singular()) { // dont display in single view, remove if not needed
            echo catch_that_image();
        }
        // new code ends

        // Post thumbnail.
        twentyfifteen_post_thumbnail();
    ?>

    <header class="entry-header">

After this you surely need to add some styling to the new image. Look inside the code, you can style it with the class my-custom-post-image.