In WordPress, a "Featured Image" is an image that represents a post, page, or custom post type. It is frequently used to visually represent content in a variety of places on a website, including blog post lists, homepage sliders, and the post itself when viewed. When a post is shared on a social media platform such as Facebook or Twitter, the featured image is typically displayed alongside the post link, making the content more appealing and clickable.
Typically, to set a featured image in the WordPress post editor, navigate to the "Featured Image" meta box, click "Set featured image," and then select or upload an image from the media library. But what if you frequently forget to set featured images for your posts? Add the below code to your theme's functions.php file. It will set the first image in the post content as the featured image if you already haven't set a featured image for your post.
function themesdna_auto_set_featured_image($post_id) {
if (wp_is_post_revision($post_id) || has_post_thumbnail($post_id)) {
return;
}
$post = get_post($post_id);
$content = $post->post_content;
$matches = [];
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $content, $matches);
if ($matches) {
$image_url = $matches['src'];
$image_id = attachment_url_to_postid($image_url);
if ($image_id) {
set_post_thumbnail($post_id, $image_id);
}
}
}
add_action('save_post', 'themesdna_auto_set_featured_image');
Note:
The above code works with images regardless of whether they are attached to the post, as long as they are embedded in the content. But it will fail if the image URL is from an external source.