Custom Function Solution
This function automatically sets the featured image by getting the first image from a post's content when the post is saved.
Add this code to your theme's functions.php
file:
This function hooks into WordPress when a post is saved and sets the featured image:
function set_featured_image_from_first_image($post_id) {
// Skip if this is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// Skip if featured image is already set
if (has_post_thumbnail($post_id))
return;
// Get post content
$post = get_post($post_id);
$content = $post->post_content;
// Find first image in content
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
if (!empty($matches[1][0])) {
$first_img_url = $matches[1][0];
// Get image ID from URL
$image_id = attachment_url_to_postid($first_img_url);
if ($image_id) {
// Set featured image
set_post_thumbnail($post_id, $image_id);
}
}
}
add_action('save_post', 'set_featured_image_from_first_image');
Alternative Plugin Solutions
If you prefer a plugin solution, these options work well:
-
Auto Post Thumbnail - Automatically generates featured images from the first image in posts
-
Quick Featured Images - Bulk set featured images and includes auto-set rules
Important Notes
- The custom code solution works only with images uploaded to your WordPress media library
- It triggers when you save or update a post
- It won't overwrite existing featured images
- Images must be properly inserted into the post content using the WordPress editor
Customization Tips
To modify the function to also work with external images, add this alternative code to your functions.php
:
This version includes support for external images:
function set_featured_image_from_first_image_extended($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (has_post_thumbnail($post_id))
return;
$post = get_post($post_id);
$content = $post->post_content;
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
if (!empty($matches[1][0])) {
$first_img_url = $matches[1][0];
$image_id = attachment_url_to_postid($first_img_url);
if (!$image_id) {
// Download and attach external image
$upload = media_sideload_image($first_img_url, $post_id, '', 'id');
if (!is_wp_error($upload)) {
set_post_thumbnail($post_id, $upload);
}
} else {
set_post_thumbnail($post_id, $image_id);
}
}
}
add_action('save_post', 'set_featured_image_from_first_image_extended');
This extended version will:
- Work with both internal and external images
- Download external images to your media library
- Set them as featured images automatically