Archived topic
Set fetchpriority="high" to image block
5 replies · Started by Israel on March 20, 2023
Hi,
I have an image that is loading above the fold and I need to set the fetchpriority="high" to fix my LCP issue (core web vitals).
The image is dynamic and different for every product's page. I searched in the editor to add the fetchpriority value to my image block but haven't found anything.
Thanks for your help.
Hi there,
try adding this PHP Snippet to your site:
function db_add_image_attr( $block_content, $block ) {
if (
! empty( $block['attrs']['className'] )
&& 'atf' === $block['attrs']['className']
) {
$block_content = str_replace( '>', 'fetchpriority="high">', $block_content );
}
return $block_content;
}
add_filter( 'render_block', 'db_add_image_attr', 10, 2 );
Then select the Image Block, and give it a class of atf and that should add the attribute for you.
That doesn't work. It adds the fetchpriority to the block and not the image itself, and due to that reason, it doesn't have any impact on core web vitals.
Hi Israel,
Can you try this snippet instead?:
function db_add_image_attr( $block_content, $block ) {
if (
! empty( $block['attrs']['className'] )
&& 'atf' === $block['attrs']['className']
) {
$block_content = str_replace( '<img', '<img fetchpriority="high"', $block_content );
}
return $block_content;
}
add_filter( 'render_block', 'db_add_image_attr', 10, 2 );
That worked! thanks :)
You're welcome, Israel! :)