WordPress blocks: can't define the image size manually in “function” smart action

Hi, I’m creating a WP plugin with a custom dynamic block and I need to customize the srcset attribute in the image I’m using.

To do that, I can simply add a “function” smart action and change the attribute directly by using PG_Blocks::getImageUrl() like this:

echo PG_Blocks::getImageUrl( $args, 'my_block_image', 'medium_large' ) . ' 1x, ' . PG_Blocks::getImageUrl( $args, 'my_block_image', 'large' ) . ' 2x';

Well, the generated block PHP code is broken (which is related to #7632), but even if I correct it manually in the block code, setting the image size in the getImageUrl() method to, let’s say, medium_large, large or any other value that is not medium, always return the medium size.

I noticed that the same occurs when I select another image site in the “use as image” field on a regular Javascript block. The method does not respect the requested image size. So it’s not a PHP thing.

Here’s a test project if you need to take a look.

1 Like

I ended up using the getImageField() from Pinegrow to get the image ID and then the native WordPress function wp_get_attachment_image_src to get the URL of the correct image size.

// Get the image ID.
$img_id = PG_Blocks::getImageField( $args, 'my_block_image', 'id', true);

// Get the correct URL for the intended image size.
$img_url = wp_get_attachment_image_src( $img_id, 'medium' )[0];

It solves both the broken generated code and the issues with the incorrect image size.

1 Like