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:
-
Auto Featured Image - Simple plugin that sets the first image as featured image
-
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