Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gutenberg custom block with responsive images

I followed this tutorial on how to build a custom WordPress Gutenberg Block: https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/

This first block is nice, but I would like to use a custom images size in this block. This image size should the also be responsive, that means on the front end srcset attributes to other image sizes should be added.

I'm searching the internet for a long time but didn't find something. With the standard image-block or gallery-block resized images from wordpress are used but for me this whole code is too complicated to follow because I am not yet used to the Gutenberg way of coding...

Is there any existing guide or code example on how this could be achieved?

Best Lukas

like image 545
Luke Avatar asked Dec 23 '22 04:12

Luke


1 Answers

I found a solution with a help of this gutenberg github issue. The simple answer is, that wordpress (php) converts all images with the class name of wp-image-<id> automatically responsive, using the wp_make_content_images_responsive-function.

That said, all you need to do is to add the above class name to your image in the save function.

Applied to the example you mentioned it would be something like the follwing:

save: function( props ) {
  var attributes = props.attributes;
  var alignment = props.attributes.alignment;
  var imageClass = 'wp-image-' + props.attributes.mediaId;

  return (
    el( 'div', { className: props.className },
      attributes.mediaURL &&
      el( 'div', { className: 'nelio-testimonial-image', style: { backgroundImage: 'url('+attributes.mediaURL+')' } },
        el( 'img', { src: attributes.mediaURL, class: imageClass } ),
      ),
      el( 'div', { className: 'nelio-testimonial-content', style: { textAlign: attributes.alignment } },
        attributes.testimonial && el( 'p', {}, attributes.testimonial ),
        el( 'p', { className: 'nelio-testimonial-name' }, attributes.name ),
        attributes.position && el( 'p', { className: 'nelio-testimonial-position' }, attributes.position )
      )
    )
  );
},
like image 85
niklas Avatar answered Dec 29 '22 00:12

niklas