Fill empty GenerateBlocks image block alt tags

When images are added to the page, whether that be a core image block or a GB image block, its data is saved as static HTML. Updating the attachments meta eg. alt tag after an image has been added in the block editor won’t update the front end. This can only happen if the image was dynamic.

The following filter will import the image alt tags from the media library and fill the empty GB image block alt tags in the front end.

add_filter( 'render_block', function( $content, $block ) {
	if (
		'generateblocks/image' !== $block['blockName'] ||
		! isset( $block['attrs']['mediaId'] )
	) {
		return $content;
	}

	$image_alt = get_post_meta($block['attrs']['mediaId'], '_wp_attachment_image_alt', TRUE);

	return preg_replace(
		'/(alt=")([^"]*)(")/',
		"$1{$image_alt}$3",
		$content
	);

}, 10, 2 );