Use the First Image in a Post as the Thumbnail in WordPress

To add a thumbnail to a post in WordPress, you need to manually add a “featured image” from the post editor. It’s possible to automatically use the first image in a post as the post’s thumbnail. Many themes do this automatically. There are also plugins that do this; one such plugin is Auto Post Thumbnail. However, if you don’t want to download a whole plugin, you can simply use the snippet below.

add_filter('get_post_metadata', function($value, $object_id, $meta_key, $single) {
	if ($meta_key !== '_thumbnail_id' || $value) {
		return $value;

	preg_match('~<img[^>]+wp-image-(\\d+)~', get_post_field('post_content', $object_id), $matches);
	if ($matches) {
		return $matches[1];
	return $value;
}, 10, 4);
After inserting this snippet, you can use built-in WordPress functions normally. WordPress functions such as has_post_thumbnail() and the_post_thumbnail() all behave as if the first image in the post is the post’s thumbnail. This snippet only works for images added to posts as WordPress attachments. If you added images using WordPress’s post editor, this this should work. If you added images using a plugin or HTML, this snippet may not work. This is because this snippet expects the post to contain an image tag in a specific format. If you didn’t insert the image using WordPress’s post editor, the image tag may not follow the format that the snippet expects.

How it works

This snippet works by intercepting calls to get_post_metadata(). WordPress thumbnails are post metadata. Functions such as  has_post_thumbnail() and the_post_thumbnail() all use get_post_metadata() to fetch thumbnails. When they attempt to fetch a post’s thumbnail from the database, the function in the snippet looks for image tags in the post content. If it finds an image tag with the appropriate class, it returns the attachment ID extracted from the image tag. Image tags inserted by WordPress’s post editor look something like this:

<img class="wp-image-123" src="...">

6 thoughts on “Use the First Image in a Post as the Thumbnail in WordPress”

  1. Well, I found a problem with it that I hope you have an answer for.

    I simply wanted to use the function to place thumbnails on a post excerpt page, but didn’t realize that it actually permanently changes the first image of a post into the Featured Image for that post. Is there any way to avoid that?


  2. After adding this code into my website functions.php file, showing the featured image with post excerpts. But there is some problem. This code showing me double images in my post.

    Can this possible that it show featured image only with excerpts, not in the blog post again.

    Please provide a solution.

Leave a Reply

Your email address will not be published. Required fields are marked *