Code Snippet to Automatically Set Featured Image from First Post Image

Jorge M Feb 3, 2025 Featured Images
How can I make my blog automatically use the first image in a post as the featured image?
What code snippet can I use in my theme's `functions.php` file to automatically set the featured image to the first image in the post content?
Andy answered Feb 3, 2025

Solution to Automatically Set Featured Image

Custom Code Solution

Add this code to your theme's functions.php file or in a site-specific plugin. The code scans the post content for the first image when saving a post and sets it as the featured image if no featured image exists.

Here's the main function that handles the automatic featured image setting:

function set_featured_image_from_first_post_image($post_id) {
    // Skip if post already has featured image
    if (has_post_thumbnail($post_id)) {
        return;
    }

    // Get post content
    $post = get_post($post_id);
    $content = $post->post_content;

    // Search for first image in the content
    preg_match_all('/<img[^>]+>/i', $content, $images);

    if (empty($images[0])) {
        return;
    }

    // Get first image src
    preg_match('/src="([^"]+)/i', $images[0][0], $src);
    
    if (empty($src[1])) {
        return;
    }

    // Download and attach image to post
    $upload = media_sideload_image($src[1], $post_id, '', 'id');
    
    if (!is_wp_error($upload)) {
        set_post_thumbnail($post_id, $upload);
    }
}

Add this hook to activate the function:

add_action('save_post', 'set_featured_image_from_first_post_image', 10, 1);

Plugin Solutions

If you prefer a plugin solution, here are reliable options:

  1. Auto Featured Image - Simple plugin that sets the first image as featured image
  2. Quick Featured Images - More advanced options for bulk management of featured images

Additional Notes

  • The code runs when saving/updating a post
  • It only sets the featured image if one isn't already set
  • Works with both uploaded images and external images
  • Handles proper attachment creation in the media library

Remember to:

  • Back up your site before adding custom code
  • Test the functionality on a staging environment first
  • Consider performance impact on sites with many posts