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/a9ea7a3def48c145f4eca7de538a6de2 to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/a9ea7a3def48c145f4eca7de538a6de2 to your computer and use it in GitHub Desktop.
Exclude images without specific class/attribute from WP Rocket lazyload [WordPress]
//rocket_buffer in theory should work no matter if gallery/slider is in the_content or not, inserted via js etc
//they don't have class and it's not possibleto assignit specifically to img elements -- here is what we can do
//we need to know: smallest parent element that contains them all
//checked -- it doesn't impact those exclusions added via ui
add_filter('rocket_buffer', 'sz_exclude_images_without_class_from_ll');
function sz_exclude_images_without_class_from_ll($buffer) {
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML($buffer);
$xpath = new DOMXpath($document);
$expression = './/figure[contains(concat(" ", normalize-space(@class), " "), " wp-block-gallery ")]';
foreach ($xpath->evaluate($expression) as $parentelement) {
//get all images inside the parent node (img can be changed to picture tag)
$imgs = $parentelement->getElementsByTagName('img');
if ($imgs->length > 0) { //if there are images found
$i = 0;
foreach ($imgs as $img) if ($i < 1) { //ajust limit number here (for slider or gallery for example)
$image_src = $img->getAttribute('src'); //get image src
$image_srcs[] = $image_src; //all images' src
$i += 1; //counter
}
}
break; //take the first parent element only if there are few
}
//Add what our list to the WPR LL exclusion!
add_filter('rocket_lazyload_excluded_attributes', function ($attributes = []) use ($image_srcs) {
$attributes = array_merge($attributes, $image_srcs);
return $attributes;
});
return $buffer; //return buffer content unchanged
}
@sabrina-zeidan
Copy link
Author

Doesn’t work — no-lazy added after lazyload script initialized — sequence is not right

@sabrina-zeidan
Copy link
Author

the first version via JS didn't work (but I guess it might with some tweaking with passing variables back via AJAX.
But the updated one via WP Rocket PHP filters direct -- works :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment