Display image from post content if no featured image

The image_size parameter allows you to include an image in your Display Posts listing of any size you like.

Here’s the description from the documentation:

image_size
Specify an image size for displaying the featured image, if the post has one. The image_size can be set to thumbnail, medium, large (all controlled from Settings > Media), or a custom image size. See Image Alignment
Default: empty
Example: [display-posts image_size="thumbnail"]

But this only works if your posts have a featured image specified. If you have inserted images directly into your content area and not set them as featured, the listing will not include those images.

The code below adds a fallback for the “first attached” image. This is the first image you uploaded when creating or editing your post, which is most often the first image that appears in the post. We’re not able to parse the post content and find the actual first image, but this is a good enough proxy.

This code snippet goes in a core functionality plugin or Code Snippets.

/**
 * Display Posts, use first attached image
 * @link https://displayposts.com/2019/10/16/display-image-from-post-content-if-no-featured-image/
 */
function be_dps_first_image( $output, $original_atts, $image, $title, $date, $excerpt, $inner_wrapper, $content, $class, $author, $category_display_text ) {

	// Only run if image_size is set and no featured image
	if( empty( $original_atts['image_size'] ) || !empty( $image ) )
		return $output;

	$images = new WP_Query( array(
		'post_parent'			=> get_the_ID(),
		'post_type'			=> 'attachment',
		'post_mime_type'		=> 'image',
		'post_status'			=> 'inherit',
		'posts_per_page'		=> 1,
		'order'				=> 'ASC',
		'fields'			=> 'ids',
	));

	if( !empty( $images->posts ) ) {
		$image = '<a href="' . get_permalink() . '" class="image">' . wp_get_attachment_image( $images->posts[0], $original_atts['image_size'] ) . '</a>';
		$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $category_display_text . $excerpt . $content . '</' . $inner_wrapper . '>';
	}

	return $output;
}
add_filter( 'display_posts_shortcode_output', 'be_dps_first_image', 10, 11 );

Filters used:

Published by Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributor to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.