Get the first image from each post in WordPress

July 3rd, 2017 less than 1 minute read

In this post, let’s write a custom WordPress function get_first_image to display the first image from all the posts. We can get this to work with pagination, on a static home page or an independent page. With this method we can retrieve all the first images in each post, including gallery posts. We can also get a default picture for post with no image attached.

Here is my function snippet:

function get_first_image() {
	$post  = get_post();
	$first_img = '';
	preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', do_shortcode( $post->post_content, 'gallery' ), $matches );
	  $first_img = isset( $matches[1][0] ) ? $matches[1][0] : null;

	if ( empty( $first_img ) ) {
			return get_template_directory_uri() . '/assets/images/empty.png'; // path to default image.

You can use it in function.php:

Now all we need to do is call the function in the page template like so: echo esc_html( get_first_image() ); and style the images or thumbnails.

Please leave a comment below if you know a better way or another method.



Leave a comment