krapan
1/17/2019 - 8:54 PM

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.

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:

<?php
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);