Gutenberg: Modify Image Block Markup

i admit that i was afraid of upgrading to the new gutenberg editor… either preventing my site from upgrading to v5.0 or even adding a function to keep the classic editor alive.

in developing my site, i wanted to include performance enhancements. namely, lazyloading using lozad. however, out of the box, the image block markup looks like this:

Default markup

<figure class="wp-block-image">
  <img src="IMAGE_SRC" alt="ALT TEXT"/>
  <figcaption>
    This is a caption
  </figcaption>
</figure>

lozad requires the markup to look like this, however:

<img class="lozad" data-src="IMAGE_SRC" />

so i needed to update that markup to allow for the change from src to data-src and including the class attribute

enter render_block()

/**
 * change up markup for images
 */
function gorirrajoe_image_block($block_content, $block)
{
  if ('core/image' === $block['blockName']) {
    $img       = wp_get_attachment_image_src($block['attrs']['id'], $block['attrs']['sizeSlug']);
    $img_alt   = get_post_meta($block['attrs']['id'], '_wp_attachment_image_alt', 1);
    $img_align = array_key_exists('align', $block['attrs']) ? 'float-' . $block['attrs']['align'] : '';

    $regex = '#<\s*?figcaption\b&#91;^>]*>(.*?)</figcaption\b&#91;^>]*>#s';
    preg_match($regex, $block['innerContent'][0], $img_caption_array);

    $img_caption = !empty($img_caption_array) ? '<figcaption>' . $img_caption_array[1] . '</figcaption>' : '';

    $block_content = '<figure class="wp-block-image ' . $img_align . '">
      <img data-src="' . $img&#91;0&#93; . '" alt="' . $img_alt . '" class="lozad"/>' .
      $img_caption . '
    </figure>';
  }
  return $block_content;
}
add_filter('render_block', 'gorirrajoe_image_block', 10, 2);

wow, that looks bad in a smaller frame… let’s break it down:

  • the function accepts $block_content and $block
  • if the block added to the editor is an image (core), then make some modifications to it before returning it back
  • the $block provides a lot of the image attributes, including its id, slug, alignment
  • one thing that isn’t saved in the db (anymore) is the figcaption, so we have to extract the text within the figcaption tags
  • once we have everything, rebuild the markup and return it

Final markup

<figure class="wp-block-image">
  <img data-src="IMAGE_SRC" alt="ALT TEXT" class="lozad"/>
  <figcaption>
    CAPTION
  </figcaption>
</figure>

Related Posts