[WordPress PHP] Automatically Set Featured Image from Post Content

What Does The Script Do?

This WordPress PHP script will automatically set a featured image in a post.

This is useful if you have forgotten to set a featured image.

It does this by:

  1. Triggering when a post is saved
  2. Checking the post type supports a featured image
  3. Checking the post does not already have a featured image attached
  4. Getting the post content
  5. Getting the first image in the post content
  6. Checking if the image is already in the media library
    1. If it is not, adding the image to the media library
  7. Setting the image as the featured image for the post

How Does It Work?

Let’s go through the code together:

The function set_featured_image_on_save($post_id) is triggered when you save a post. It receives the ID of the saved post as an argument.

First, it checks if the post type supports the ‘thumbnail’ feature, which is used for featured images. If the post type doesn’t support the feature, the function stops running and returns nothing.

Then, it checks if the post already has a featured image. If it does, again, the function stops running.

Next, the function extracts the content of the post using get_post($post_id).

It then searches the content for any images using a regular expression pattern. If it finds an image, it checks if the image already exists in the media library using the attachment_url_to_postid($image_url) function.

If the image doesn’t exist in the media library, it downloads the image, saves it to the upload directory, and adds it to the media library. This is done using a series of functions including wp_upload_dir(), file_get_contents(), file_put_contents(), wp_check_filetype(), wp_insert_attachment(), wp_generate_attachment_metadata(), and wp_update_attachment_metadata().

Finally, if all the previous steps are successful, it sets the downloaded image as the featured image for the post using set_post_thumbnail($post_id, $attach_id).

The function is added to the save_post action hook, which means it will run every time a post is saved.

Considerations

  • Permissions: Make sure your WordPress installation has the necessary permissions to read and write files to the upload directory.
  • Performance: If your posts contain a lot of images, this script could slow down the saving process as it has to download and process images.
  • Image Choice: The script uses the first image it finds in the post. If you want a different image as your featured image, you’ll need to manually set it.
  • Post Types: By default, this function applies to all post types that support the ‘thumbnail’ feature. If you want to limit it to specific post types, you’ll need to modify the script.

WordPress PHP Script

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

/**
 * Automatically set featured image for posts without one.
 */
function set_featured_image_on_save($post_id) {
    // Check if post type supports featured image
    $post_type = get_post_type($post_id);
    
   if (!post_type_supports($post_type, 'thumbnail')) { // the 'thumbnail' feature, which is used for featured image
        return;
    }
    
    // Check if post has a featured image
    if (has_post_thumbnail($post_id)) {
        return;
    }
    
    // Get the post content
    $post = get_post($post_id);
    $post_content = $post->post_content;
    
    // Search content for images
    $pattern = '/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i';
    preg_match($pattern, $post_content, $matches);
    
    if (isset($matches[1])) {
        $image_url = $matches[1];
        
        // Check if the image is already in the media library
        $attach_id = attachment_url_to_postid($image_url);
        
        // If the image doesn't exist in the media library, add it
        if (empty($attach_id)) {
            $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);
            $attach_data = wp_generate_attachment_metadata($attach_id, $file);
            wp_update_attachment_metadata($attach_id, $attach_data);
        }
        
        // Add the image as the featured image for the post
        set_post_thumbnail($post_id, $attach_id);
    }
}

add_action('save_post', 'set_featured_image_on_save');