When a post is saved without a featured image, use the first image in its content automatically.
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 );
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.
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.
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.