This will only work if the media item was added to the library while on the particular post’s editor. I cooked up code to traverse the blocks, but it requires you to edit for each new block.
Was wondering if anybody came across a “catch all” solution for adding images to the Yoast sitemap.