How To Automatically Set First Image As WordPress Thumbnail

Hemant Magar

| June 22, 2025

Whenever We Publish A Blog Post In WordPress, The Thumbnail Or Featured Image Plays A vital Role. It appears on blog listing pages (home page, category page, etc), social media previews, as well as in Search results.

In simple words, It’s The First Impression Of Your Article – That can increase or decrease the CTR Of your blog posts. But Here’s The Problem:

Some WordPress Themes ( Lightweight Or Custom developed) don’t Automatically Pick A Thumbnail From The Post. If you forget to set it manually, your post might look broken or incomplete on the homepage.

That’s Why It’s Super Important That Every Blog Post Has A Thumbnail.

Problem: Theme Doesn’t Pick the First Image As the Thumbnail

In many themes, if you forget to set a featured image while publishing the post, the post will show up without a featured image.

This Breaks The post loop layout — Especially If You’re Using A Grid View Where All Posts Have Images. This Looks Unprofessional And Confusing For Visitors. But The Good News Is — We Can Fix It With A Few Lines Of Code (No Plugin Needed).

Why We’re Not Using Any Plugin

Yes, Various Plugins can set first image as WordPress thumbnail. But Here’s The Catch:

  1. Plugins Add Extra Load To Your Site
  2. They Can Conflict With Your Theme Or Other Plugins
  3. And They Might Slow Down Your Website

That’s why the best way is to use a small amount of PHP code. It’s Clean, Lightweight, And Only Runs When Needed.

What We’re Going To Do To Set The First Image As WordPress Thumbnail?

We Will Write A Short PHP Code That Will Do This:

  1. First – It Checks If The Post Already Has A Featured Image
  2. If Not, It Automatically Picks The First Image From The Post Content
  3. Then – It Sets That Image As The Featured Image

And Boom💥 Your Blog Will Never Have A Missing Thumbnail Again!

How To Set First Image As WordPress Thumbnail Step By Step

Step 1

Step 1 Log in To Your WordPress Dashboard & Go To Appearance > Theme File Editor As Shown In the Above Image.

Step 2

Step 2 Check For The “Functions.php” File In Your Theme & Open The Functions.php File As Shown InThe Above Image

Step 3

Step 3 Now Add The Code Given In the Following Post In Your functions.php file At the End As Shown In Above Image

Step 4

Step 4 Update (Save) The Funtions.php File As Shown In The Above Image

Code To Set Featured Image :

function set_featured_image_automatically($post_id) {
    // If post already has a thumbnail, do nothing
    if (has_post_thumbnail($post_id)) {
        return;
    }

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

    // Search for first image
    preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);

    if (isset($matches[1])) {
        $image_url = $matches[1];

        // Upload the image to media library
        $upload_dir = wp_upload_dir();
        $image_data = file_get_contents($image_url);
        $filename = basename($image_url);

        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
        }

        file_put_contents($file, $image_data);

        $wp_filetype = wp_check_filetype($filename, null);
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title'     => sanitize_file_name($filename),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        $attach_id = wp_insert_attachment($attachment, $file, $post_id);
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        wp_update_attachment_metadata($attach_id, $attach_data);
        set_post_thumbnail($post_id, $attach_id);
    }
}

add_action('save_post', 'set_featured_image_automatically');

How Does This Code work?

  1. First, It Checks If The Post Already Has A Thumbnail Set.
  2. If No Thumbnail Is Found, It Scans Your Post Content To Find The First Tag.
  3. Once Found, It Uploads That Image To The WordPress Media Library.
  4. Finally, It Automatically Sets That Image As The Featured Image (Thumbnail) For That Post.

Conclusion: How To Automatically Set The First Image As WordPress Thumbnail

This Method Works Best If You Always Add At Least One Image In Your Blog Posts. If There’s No Image In The Post, The Code Simply Does Nothing.

Also, be careful If You’re Using Auto-Import Tools Or Plugins That Pull In External Content.
It Might Create Duplicate Uploads Or Conflict With Those Scripts.

And Don’t Worry! This Code Doesn’t Run Every Time A Visitor Opens Your Post. It Only Runs When You Save Or Update A Post From The Admin Panel.

So Use It Smartly. And It’ll Keep Your Blog Layout Clean And Professional, Without Any Missing Thumbnails!


About Author

Hemant Magar Author

Hello, Myself Hemant. I Am Web Developer & Likes To Create Awesome Projects By Using MERN, Java, Python, C++. In This Website You Will Get Cool Projects Made With Above Technologies With Full Source Code.

Leave a Reply

Your email address will not be published. Required fields are marked *

Notes

Interview Questions

Elements

CMS

  • Generatepress Theme For Blogger
  • Add TOC In Blogger
  • Host Fonts Locally In WordPress
  • Blogger Theme Dev From Scratch

Share This Post