Skip to content

Commit

Permalink
Fix: Stop crashing with Lightbox on image blocks without an image.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dmsnell committed Oct 11, 2023
1 parent ce8aed4 commit 103c67c
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/wp-includes/blocks/image.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 '';
Expand Down Expand Up @@ -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, '<img' ) ) {
return $block_content;
}

$processor = new WP_HTML_Tag_Processor( $block_content );

$aria_label = __( 'Enlarge image' );

$processor->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.
Expand Down

0 comments on commit 103c67c

Please sign in to comment.