Show the Latest Featured Image from Featured Content

For the latest ThemeShaper remake, we added Featured Content to Twenty Sixteen. That’s standard, but our design called for not showing the featured image of every post, but only the latest post. That image serves as a backdrop to our collection of featured posts, which can be from one to three posts at a time. It’s a neat design pattern, so I thought I’d share the code needed to grab that image.

First, I assume you have featured content set up like the example code from the Jetpack documentation suggests. Next, let’s write a function to grab that image:

function mytheme_get_first_featured_featured_image() {
	$featured_posts = mytheme_get_featured_posts();
	if ( is_array( $featured_posts ) && ! empty( $featured_posts ) ) {
		$post_id = (int) $featured_posts[0]->ID;
		if ( has_post_thumbnail( $post_id ) ) {
			 $big_post_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'mytheme-custom-image-size' );
			 printf( 'style="background-image: url(%s);"', esc_url( $big_post_image[0] ) );
		}
	}
}

Using it in your theme:

<div id="featured" class="featured-posts" <?php mytheme_get_first_featured_featured_image(); ?>>

<!-- Other stuff -->

</div>

A few notes about what’s happening in the code above:

  • First, we need to grab the featured posts, and check to make sure there are some posts.
  • If there is, we assign the post ID of the latest post to a variable, $post_id. We’ll need that later.
  • Next, if the latest post has a post thumbnail, we create another variable, $big_post_image, and use it to assign the actual output of the image URL.
  • Finally, we output the markup. It outputs as a style attribute, and you can then style the rest via CSS. In your theme, you just attach the function to the div or html element you want to apply the style on.

That’s it! Hopefully, this code snippet helps you in the next theme you create. Happy theming!

Author: David A. Kennedy

I work as a Design Director at Automattic on Jetpack, focusing on the front end experience.

3 thoughts on “Show the Latest Featured Image from Featured Content”

  1. WordPress 4.4 introduced a wp_get_attachment_image_url() function, which makes the sample code more concise compared to using wp_get_attachment_image_src().

Comments are closed.