Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Last active April 13, 2023 09:59
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/40e988092e75a30c828928ae918a7a2d to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/40e988092e75a30c828928ae918a7a2d to your computer and use it in GitHub Desktop.
Exclude first image on single post from WP Rocket lazyload
//if not using rocket_lazyload_excluded_attributes filter, class remove-lazy should be added to WP Rocket settings in admin!
// + there is a helper plugin to do so in case we HAVE unique attribute to refer to https://github.com/wp-media/wp-rocket-helpers/blob/master/lazyload/wp-rocket-exclude-x-first-images-by-attribute/p
add_filter ('the_content', 'sz_add_class_to_first_img');
function sz_add_class_to_first_img($content){
if (!is_admin() && !is_user_logged_in()){ //do only on frontend for not logged-in
if ( is_singular('post') ) { //do on single posts only
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
if (count($imgs)>0){//if there are images in the content
$img = $imgs[0]; //get 1st image
$original_class = $img->getAttribute('class'); //get original class to preserve it
$img->setAttribute('class', (empty($original_class) ? 'remove-lazy' : 'remove-lazy '.$original_class)); //whether class set up or not
$content = $document->saveHTML();
}
}
}
return $content;
}
function rocket_lazyload_exclude_class( $attributes ) {
$attributes[] = 'class="remove-lazy '; //TODO: make it work regardless where class is placed
return $attributes;
}
add_filter( 'rocket_lazyload_excluded_attributes', 'rocket_lazyload_exclude_class' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment