Automatically assigns the first uploaded image as the featured image when publishing a post.
Steps
- Open your WordPress theme
functions.phpfile. - Add the code below.
- Save the file.
- Create a new post and upload images.
Done — WordPress will automatically set a featured image if one isn’t selected.
function auto_set_featured_image() {
global $post;
if (has_post_thumbnail($post->ID)) {
return;
}
$attached_image = get_children(array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => 1
));
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
add_action('save_post', 'auto_set_featured_image');
