Content & Posts PHP Intermediate

Set the First Image as the Featured Image

When a post is saved without a featured image, use the first image in its content automatically.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 26 lines
add_action( 'save_post_post', function ( int $post_id, WP_Post $post ): void {
	if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || has_post_thumbnail( $post_id ) ) {
		return;
	}

	// Image blocks store the attachment ID in the class "wp-image-123".
	if ( preg_match( '/wp-image-(\d+)/', $post->post_content, $m ) && wp_attachment_is_image( (int) $m[1] ) ) {
		set_post_thumbnail( $post_id, (int) $m[1] );
		return;
	}

	// Otherwise use the first image uploaded to this post.
	$attached = get_children( [
		'post_parent'    => $post_id,
		'post_type'      => 'attachment',
		'post_mime_type' => 'image',
		'numberposts'    => 1,
		'orderby'        => 'menu_order ID',
		'order'          => 'ASC',
		'fields'         => 'ids',
	] );

	if ( $attached ) {
		set_post_thumbnail( $post_id, (int) reset( $attached ) );
	}
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Featured images appear on blog archives, in social shares and in RSS. Writers often forget to set one, leaving a blank card. This snippet picks the first image in the post for them.

How it works

save_post_post runs whenever a post is saved. If the post has no featured image, the snippet looks for the class wp-image-{ID}, which the Image block and the classic editor both add, and checks the ID is a real image before setting it.

If the content has no image, it falls back to the first image uploaded while editing that post.

Things to watch

  • Posts that already have a featured image are never changed.
  • Older posts are only updated the next time they’re saved. To update them all, open Posts, select them, choose Bulk Edit and click Update.
  • Images inserted by URL from another site have no attachment ID and can’t be used.

How to test it

Create a post with an Image block but no featured image and save it. Reload: the image should now be set as the featured image.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only