Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active September 6, 2022 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sabrina-zeidan/bd7fb6ff6f2226e9fea898ceffadaeab to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/bd7fb6ff6f2226e9fea898ceffadaeab to your computer and use it in GitHub Desktop.
Disable native WordPress / browser lazy loading by adding class
//Disable native WP lazyloading for images by adding a CSS class lazyload-disabled in Block Editor
//Now let's make the magic happen
add_filter('wp_img_tag_add_loading_attr', 'sz_disable_ll', 10, 3);
function sz_disable_ll($value, $image, $context){
$disabled_class = 'lazyload-disabled';
if (false !== strpos($image, $disabled_class)) {
return false;
}
return $value;
}
//Now, in many cases you won't be able to add CSS class directly to the image, but it would be added to the Image block insted. Let's pass this value to the image inside the Image Block
add_filter('render_block', 'sz_disable_ll_inside_image_block', 10, 2);
function sz_disable_ll_inside_image_block($block_content, $block){
if ('core/image' !== $block['blockName']) {
return $block_content;
}
if (!empty($block['attrs']['className']) && str_contains($block['attrs']['className'], 'lazyload-disabled')) {
$block_content = mb_convert_encoding($block_content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($block_content));
$imgs = $document->getElementsByTagName('img');
if (count($imgs) > 0) { //if there are images in the content
$img = $imgs[0]; //get the 1st image
$original_class = $img->getAttribute('class'); //get original classes to preserve it
$img->setAttribute('class', (empty($original_class) ? 'lazyload-disabled' : 'lazyload-disabled ' . $original_class)); //whether class set up or not
$block_content = $document->saveHTML();
}
}
//Possible todo: add loading="eager" or/and preloading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment