Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- function get_img( $args = array() ) {
- $defaults = [
- 'img_ID' => get_post_thumbnail_id( $GLOBALS['post'] ),
- 'size' => null,
- 'before' => '<div class="lazy-wrapper">',
- 'after' => '</div>',
- ];
- $args = wp_parse_args( $args, $defaults );
- $uploads_dir = wp_upload_dir();
- $full_img_url = wp_get_attachment_image_url( $args['img_ID'], 'full' );
- list( $full_width, $full_height ) = getimagesize( $full_img_url );
- $svg_placeholder_url = preg_replace( '/\.(jpe?g|png|gif|bmp)$/i', '.svg', $full_img_url );
- $svg_placeholder_path = str_replace( $uploads_dir['baseurl'], $uploads_dir['basedir'], $svg_placeholder_url );
- $svg_content = get_file_content( $svg_placeholder_url );
- $svg_content = str_replace( '#', '%23', $svg_content ); // fix Data-URI SVG not working in Firefox: # in the content needs to be escaped as %23.
- $img_placeholder_size = empty( $args['size'] ) ? [ $full_width / 15, $full_height / 15 ] : [ $args['size'][0] / 15, $args['size'][1] / 15 ];
- $img_placeholder_url = wp_get_attachment_image_url( $args['img_ID'], $img_placeholder_size );
- $placeholder = file_exists( $svg_placeholder_path ) ? 'data:image/svg+xml;utf8,' . $svg_content : $img_placeholder_url;
- $data_src = empty( $args['size'] ) ? $full_img_url : wp_get_attachment_image_url( $args['img_ID'], [ $args['size'][0], $args['size'][1] ] );
- $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 ] ) : '';
- $data_srcset = ! empty( $retina_img_url ) ? "data-srcset='$retina_img_url 2x'" : '';
- $alt = get_post_meta( $args['img_ID'], '_wp_attachment_image_alt', true );
- $img_width = empty( $args['size'] ) ? $full_width : $args['size'][0];
- $img_height = empty( $args['size'] ) ? $full_height : $args['size'][1];
- $img = $args['before'] . "<img class='lazy' src='$placeholder' data-src='$data_src' $data_srcset alt='$alt' width='$img_width', height='$img_height' />" . $args['after'];
- return $img;
- }
Add Comment
Please, Sign In to add comment