PHP snippet · Media & Files
Auto featured image from the first content image
On save, sets the featured image from the first image in the post when none is set. One you picked yourself is never overwritten.
About this php snippet
Archive listings, related post blocks, and social sharing cards all read the featured image, so a post saved without one shows a grey placeholder even when the post itself is full of images. It is the kind of gap nobody notices until a link is shared and comes back blank.
On save, if no featured image is set, this picks the first image in the content and uses that.
What it does
- Runs on save, and only when the featured image is empty
- Finds the image two ways, in order: the image class that both the block and classic editors add, and failing that the first image tag resolved back to an attachment
- Checks that what it found is a real image attachment before setting it
- Skips autosaves and revisions, so it does not fire on every keystroke
Good to know
- A featured image you chose yourself always wins. This only ever fills an empty one.
- An image hotlinked from another domain has no attachment behind it and is skipped
- It reads the post content, so classic and Gutenberg posts are fully covered. An Elementor page keeps its layout in post meta instead, so there is usually nothing in the content for this to find.
- Existing posts are picked up the next time they are saved
- Post types without featured image support are left alone



