The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Automatically Add Featured Images to WordPress Posts

Shared by Amit Dholiya · September 24, 2026 · @save_post

14 views
2 upvotes
Back to Snippets

If you often forget to set a featured image, you can automatically use the first image inside the post content as the featured image.

Steps

  1. Add the code below to your theme’s functions.php.
  2. Publish or update a post that contains an image.
  3. If the post does not already have a featured image, WordPress will use the first image found in the content.
/**
 * Automatically set the first post image as featured image
 */
function custom_set_first_image_as_featured( $post_id ) {

    // Prevent autosave and revisions.
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
        return;
    }

    // Only process standard blog posts.
    if ( get_post_type( $post_id ) !== 'post' ) {
        return;
    }

    // Don't replace an existing featured image.
    if ( has_post_thumbnail( $post_id ) ) {
        return;
    }

    $post = get_post( $post_id );

    if ( ! $post || empty( $post->post_content ) ) {
        return;
    }

    preg_match(
        '/<img[^>]+wp-image-([0-9]+)/i',
        $post->post_content,
        $matches
    );

    if ( empty( $matches[1] ) ) {
        return;
    }

    $attachment_id = absint( $matches[1] );

    if ( $attachment_id ) {
        set_post_thumbnail( $post_id, $attachment_id );
    }
}

add_action( 'save_post', 'custom_set_first_image_as_featured', 20 );

Tested on

WordPress 7.1

Reported by the author on September 24, 2026. WPFolks has not verified this.

Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments