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 Set Featured Image from First Uploaded Image

Shared by Amit Dholiya · June 27, 2026

49 views
1 upvote
Back to Snippets

Automatically assigns the first uploaded image as the featured image when publishing a post.

Steps

  1. Open your WordPress theme functions.php file.
  2. Add the code below.
  3. Save the file.
  4. Create a new post and upload images.

Done — WordPress will automatically set a featured image if one isn’t selected.

function auto_set_featured_image() {
    global $post;

    if (has_post_thumbnail($post->ID)) {
        return;
    }

    $attached_image = get_children(array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'numberposts' => 1
    ));

    if ($attached_image) {
        foreach ($attached_image as $attachment_id => $attachment) {
            set_post_thumbnail($post->ID, $attachment_id);
        }
    }
}
add_action('save_post', 'auto_set_featured_image');
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

Proudly supported by