'How to add width and height to Wordpress Gutenberg image block output?

Default Gutenberg Image block i HTML output has no height="xxx" and width="xxx" parameters:

<div class="wp-block-image">
<figure class="aligncenter size-blog-width">
<img src="https://domain.tld/wp-content/uploads/img-640x136.jpg" alt="alt" class="wp-image-83" srcset="https://domain.tld/wp-content/uploads/img-640x136.jpg 640w, https://domain.tld/wp-content/uploads/img-300x64.jpg 300w, https://domain.tld/wp-content/uploads/img-768x163.jpg 768w, https://domain.tld/wp-content/uploads/img.jpg 814w" sizes="(max-width: 640px) 100vw, 640px">
<figcaption>something</figcaption>
</figure>
</div>

How can I force WordPress/Gutenberg to add them?

I need them (especially height) for correctly make image placeholder in lazy-load plugin.



Solution 1:[1]

The only way I found it is query selecting the image from DOM.

wp.hooks.addFilter(
  'blocks.getSaveContent.extraProps',
  'my/custom/extraProps',
  (props, type, attr) => {
    if (type.name !== 'core/image') {
      return props;
    }
    
    const el = document.querySelector(`img[src="${attr?.url}"]`);

    if(!el) {
      return props;
    }

    return lodash.assign({}, props, {
      height: el.clientHeight,
      width: el.clientWidth,
    });
  }
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rodrigo Alves