Get first image from Gutenberg-enabled WordPress post
Place in theme functions.php or similar
function get_first_image( $post_content, $size = 'thumbnail' ) { preg_match( "/wp:image {.*?\"id\":(\d+),/is", $post_content, $matches ); if ( !empty( $matches[1] ) ) { return wp_get_attachment_image( (int)$matches[1], $size ); } return ''; }
Can be used as a fallback for e.g. if the post featured image is not set, e.g.
$image = ( has_post_thumbnail() ) ? get_the_post_thumbnail( get_the_ID(), 'medium' ) : get_first_image( $post->post_content, 'medium' ); echo $image;