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

More php snippets

Your EMCP guide

Answers from our docs

YOUR CHAT, YOUR CHOICE

Before we chat

MSR Builds processes your question and up to four recent messages on our server to answer from the EMCP docs. AI is optional and needs your separate permission.

The chat is kept in this page's memory, not saved as a conversation in our database or browser storage. Our hosting and security services process connection information, such as your IP address, to prevent abuse.

Cloudflare Turnstile checks your browser and connection to prevent automated abuse when you send a question. No login is required.

Please leave out personal, sensitive or confidential information, passwords and API keys.

You can withdraw consent and clear this page's chat at any time. This cannot undo a request already sent or erase provider/security records.

Chat privacy, retention & your rights ↗ · Privacy contact

Starting chat consents to this processing. You can browse our docs without using the chat.