WordPress set featured image to first image of the post

Have you already used this image in a different post? The post_parent may already be assigned to a different post ID from the one you are on. The code you have will only return images uploaded to this post first.

I’ve seen a few regex type solutions to this problem, however I think PHPs DOMDocument may be safer. This is also very experimental but seems to work for me:

function auto_set_featured($post_id, $post, $update ) {
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML($post->post_content, LIBXML_NOWARNING);
    libxml_clear_errors();

    $images = $doc->getElementsByTagName('img');

    if($images->length > 0) {
        $first_image = $images->item(0)->getAttribute('src');
        $attachment_id = attachment_url_to_postid($first_image);
        if($attachment_id) {
            set_post_thumbnail($post_id, $attachment_id);
        }
    }
}

Should be simple enough to follow, but it loads the post content, and looks for the first img DOMElement. We then use that image URL with attachment_url_to_postid to get the attachment ID, which you pass to set_post_thumbnail as per your code.