artemsemkin

Rhye theme: disable JS lazy loading

Mar 9th, 2022 (edited)
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. <?php
  2.  
  3. // Disable theme lazy images by swapping [data-*] attributes with the original image attributes
  4. function filter_disable_lazy_images( $buffer ) {
  5.     libxml_use_internal_errors( true );
  6.     $document = new DOMDocument();
  7.     $document->loadHTML( mb_convert_encoding( $buffer, 'HTML-ENTITIES', 'UTF-8' ) );
  8.     $lazy_images = $document->getElementsByTagName( 'img' );
  9.  
  10.     foreach ( $lazy_images as $image ) {
  11.         $src    = $image->getAttribute( 'data-src' );
  12.         $srcset = $image->getAttribute( 'data-srcset' );
  13.         $sizes  = $image->getAttribute( 'data-sizes' );
  14.  
  15.         if ( ! empty( $src ) ) {
  16.             $image->setAttribute( 'src', $src );
  17.             $image->removeAttribute( 'data-src' );
  18.             $image->setAttribute( 'loading', 'lazy' );
  19.         }
  20.  
  21.         if ( ! empty( $srcset ) ) {
  22.             $image->setAttribute( 'srcset', $srcset );
  23.             $image->removeAttribute( 'data-srcset' );
  24.         }
  25.  
  26.         if ( ! empty( $sizes ) ) {
  27.             $image->setAttribute( 'sizes', $sizes );
  28.             $image->removeAttribute( 'data-sizes' );
  29.         }
  30.     };
  31.  
  32.     return $document->saveHTML();
  33. }
  34.  
  35. function buffer_start() {
  36.     ob_start( 'filter_disable_lazy_images' );
  37. }
  38.  
  39. function buffer_end() {
  40.     ob_end_flush();
  41. }
  42.  
  43. add_action( 'wp_head', 'buffer_start' );
  44. add_action( 'wp_footer', 'buffer_end' );
Add Comment
Please, Sign In to add comment