Altering images inserted into Posts for lazyloading w/ Simple HTML DOM Parser
-
Hello,
I posted this ame question to WP answers earlier, if you want points I’ll be happy to approve your answer π
I want to find a robust solution to make lazyloading possible for images inserted into a post. There are many lazyload solutions out there. I’m not looking to cater any one of them specifically, but rather just a method to edit the dom with PHP without regex.
The Simple HTML DOM Parser seems perfect for that, I’m just not sure what I’m doing here.
I can find all images and edit the attributes to suit a lazyload script:
// Add the PHP Dom parser require "assets/simple_html_dom.php"; function add_image_placeholders( $content ) { $html = str_get_html($content); // Find all images foreach($html->find('img') as $element) { $img_src = $element->src; $placeholder = 'data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='; $img_class = $element->class . " lazy"; $img_width = $element->width; $img_height = $element->height; $img_id = $element->id; $img_alt = $element->alt; $img_title = $element->title; echo '<img src="' . $placeholder . '" data-original="' . $img_src . '" width="' . $img_width . '" height="' . $img_height . '" class="' . $img_class . '" alt="' . $img_alt . '"> <br>'; } return $html; } add_filter( 'the_content', 'add_image_placeholders', 99 );That works, in a way, but of course it just clumps the images in the beginning of the post. I would need to loop the whole content somehow… So that the images stay on their place in the content.
Here’s little bit about how to customise the parsing behavious, but I could’t get it work.
Thanks π
The topic ‘Altering images inserted into Posts for lazyloading w/ Simple HTML DOM Parser’ is closed to new replies.