Get the First or Featured Image in WordPress

There are several ways to get the first or Featured Image in WordPress for use on a Home page blog feed, an Archives page feed, etc. The method below first checks for a Featured Image, then for the first attached image, and finally a default image if needed. This also allows you to designate the initial size (thumbnail, medium, large or full), while using the native WordPress responsive image support by including srcset and sizes attributes to the image. Browsers will download the most appropriate size and ignore the others.

<?php
function evo_thumbnail_image() {
	if ( has_post_thumbnail() ) {
		the_post_thumbnail( 'medium' );
	} else {
		global $post;
		$args = array(
			'post_type'   => 'attachment',
			'numberposts' => -1,
			'post_status' => null,
			'post_parent' => $post->ID
		);
		$attachments = get_posts( $args );
		if ( $attachments ) {
			echo wp_get_attachment_image( $attachments[0]->ID, 'medium', false, array( 'class'=>'img-responsive' ) );
		} else {
			echo '<img src="' . get_stylesheet_directory_uri() . '/assets/images/default-post-image.png' . '" />';
		}
	}
}

Use the function in the loop like this.

<?php evo_thumbnail_image() ?>

If only the Featured Image is needed, the method below will work.

<?php the_post_thumbnail( 'medium' ); ?>