Guest User

Untitled

a guest
Dec 13th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. <?php
  2.  
  3. function get_img( $args = array() ) {
  4. $defaults = [
  5. 'img_ID' => get_post_thumbnail_id( $GLOBALS['post'] ),
  6. 'size' => null,
  7. 'before' => '<div class="lazy-wrapper">',
  8. 'after' => '</div>',
  9. ];
  10.  
  11. $args = wp_parse_args( $args, $defaults );
  12.  
  13. $uploads_dir = wp_upload_dir();
  14. $full_img_url = wp_get_attachment_image_url( $args['img_ID'], 'full' );
  15.  
  16. list( $full_width, $full_height ) = getimagesize( $full_img_url );
  17.  
  18. $svg_placeholder_url = preg_replace( '/\.(jpe?g|png|gif|bmp)$/i', '.svg', $full_img_url );
  19. $svg_placeholder_path = str_replace( $uploads_dir['baseurl'], $uploads_dir['basedir'], $svg_placeholder_url );
  20.  
  21. $svg_content = get_file_content( $svg_placeholder_url );
  22. $svg_content = str_replace( '#', '%23', $svg_content ); // fix Data-URI SVG not working in Firefox: # in the content needs to be escaped as %23.
  23.  
  24. $img_placeholder_size = empty( $args['size'] ) ? [ $full_width / 15, $full_height / 15 ] : [ $args['size'][0] / 15, $args['size'][1] / 15 ];
  25. $img_placeholder_url = wp_get_attachment_image_url( $args['img_ID'], $img_placeholder_size );
  26.  
  27. $placeholder = file_exists( $svg_placeholder_path ) ? 'data:image/svg+xml;utf8,' . $svg_content : $img_placeholder_url;
  28. $data_src = empty( $args['size'] ) ? $full_img_url : wp_get_attachment_image_url( $args['img_ID'], [ $args['size'][0], $args['size'][1] ] );
  29.  
  30. $retina_img_url = $full_width >= $args['size'][0] * 2 && ! empty( $args['size'] ) ? wp_get_attachment_image_url( $args['img_ID'], [ $args['size'][0] * 2, $args['size'][1] * 2 ] ) : '';
  31. $data_srcset = ! empty( $retina_img_url ) ? "data-srcset='$retina_img_url 2x'" : '';
  32.  
  33. $alt = get_post_meta( $args['img_ID'], '_wp_attachment_image_alt', true );
  34.  
  35. $img_width = empty( $args['size'] ) ? $full_width : $args['size'][0];
  36. $img_height = empty( $args['size'] ) ? $full_height : $args['size'][1];
  37.  
  38. $img = $args['before'] . "<img class='lazy' src='$placeholder' data-src='$data_src' $data_srcset alt='$alt' width='$img_width', height='$img_height' />" . $args['after'];
  39.  
  40. return $img;
  41. }
Add Comment
Please, Sign In to add comment