From 103c67cadcd6d3d6aeef595f40c3ced8f11bd5d5 Mon Sep 17 00:00:00 2001 From: Dennis Snell Date: Wed, 11 Oct 2023 06:02:18 -0700 Subject: [PATCH] Fix: Stop crashing with Lightbox on image blocks without an image. Resolves WordPress/Gutenberg#55217 When rendering images with the lightbox "expand on click" function enabled, if an image block is encountered with no image (for example, a block was added but no image was ever selected), then WordPress would create a warning that an "undefined array key 0" was being accessed because the server code assumes an IMG element exists in the block's HTML. In this patch a check is performed to ensure that an IMG block exists before processing the block. If one isn't, for any reason, the original given HTML for the block is passed through un-modified. This patch needs to be backported into Gutenberg from where it's sourced but this issue arose during the WordPress 6.4 beta testing and needs to be resolved immediately in Core. --- src/wp-includes/blocks/image.php | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/wp-includes/blocks/image.php b/src/wp-includes/blocks/image.php index e1f71964622c0..c02ce6b4c874c 100644 --- a/src/wp-includes/blocks/image.php +++ b/src/wp-includes/blocks/image.php @@ -16,9 +16,7 @@ * @return string The block content with the data-id attribute added. */ function render_block_core_image( $attributes, $content, $block ) { - $processor = new WP_HTML_Tag_Processor( $content ); - $processor->next_tag( 'img' ); if ( $processor->get_attribute( 'src' ) === null ) { return ''; @@ -123,11 +121,28 @@ function block_core_image_get_lightbox_settings( $block ) { * @return string Filtered block content. */ function block_core_image_render_lightbox( $block_content, $block ) { + /* + * If it's not possible that an IMG element exists then return the given + * block content as-is. It may be that there's no actual image in the block + * or it could be that another plugin already modified this HTML. + */ + if ( false === stripos( $block_content, 'next_tag( 'img' ); + /* + * If there's definitely no IMG element in the block then return the given + * block content as-is. There's nothing that this code can knowingly modify + * to add the lightbox behavior. + */ + if ( ! $processor->next_tag( 'img' ) ) { + return $block_content; + } + $alt_attribute = $processor->get_attribute( 'alt' ); // An empty alt attribute `alt=""` is valid for decorative images.