# Set the Featured Image Automatically

> When a post is saved without a featured image, uses the first image attached to it or the first image block in its content.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: content, featured-image, thumbnail
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/auto-set-featured-image/

## Code

```php
add_action( 'save_post', function ( $post_id, $post ) {
    if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || 'auto-draft' === $post->post_status ) {
        return;
    }

    if ( ! post_type_supports( $post->post_type, 'thumbnail' ) || has_post_thumbnail( $post_id ) ) {
        return;
    }

    if ( preg_match( '/wp-image-(\d+)/', $post->post_content, $match ) && wp_attachment_is_image( (int) $match[1] ) ) {
        set_post_thumbnail( $post_id, (int) $match[1] );
        return;
    }

    $images = get_attached_media( 'image', $post_id );

    if ( $images ) {
        $first = reset( $images );
        set_post_thumbnail( $post_id, $first->ID );
    }
}, 10, 2 );
```

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Set the Featured Image Automatically" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
