Last active
March 12, 2021 14:27
-
-
Save hereswhatidid/d3e46b3d215587ce10cd3d8fcf3ff25e to your computer and use it in GitHub Desktop.
Generate the image HTML with a limited srcset range of sizes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace RMG\PageSpeed; | |
/** | |
* Get the HTML for an image with limited srcset sizes | |
* | |
* @param string|int $image_id | |
* @param string $size The image size name ex. `medium`, `thumb` | |
* @param boolean $icon | |
* @param null|array $attrs | |
* | |
* @return false|string | |
*/ | |
function get_image_maxsize( $image_id, $size, $icon = false, $attrs = [] ) { | |
if ( ! $image_src = wp_get_attachment_image( $image_id, $size, $icon, $attrs ) ) { | |
return false; | |
} | |
$link_dom = new \DOMDocument(); | |
$link_dom->loadHTML( $image_src ); | |
foreach ($link_dom->getElementsByTagName('img') as $item) { | |
$srcset = $item->getAttribute( 'srcset' ); | |
$updated_srcset = \RMG\PageSpeed\limit_srcset_values( $srcset, $size ); | |
$item->setAttribute('srcset', $updated_srcset); | |
$image_src = $link_dom->saveHTML(); | |
} | |
return $image_src; | |
} | |
function limit_srcset_values( $srcset, $size ) { | |
$sizes = wp_get_registered_image_subsizes(); | |
if ( ! array_key_exists( $size, $sizes ) ) { | |
return false; | |
} | |
$max_width = intval( $sizes[$size]['width'] ); | |
$sizes = []; | |
$src_items = explode( ', ', $srcset ); | |
foreach( $src_items as $item ) { | |
$item_props = explode( ' ', $item ); | |
$item_width = intval( str_replace( 'w', '', $item_props[1] ) ); | |
if ( $item_width <= $max_width ) { | |
$sizes[] = $item; | |
} | |
} | |
return implode( ', ', $sizes ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment