Skip to content

Instantly share code, notes, and snippets.

@hereswhatidid
Last active March 12, 2021 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hereswhatidid/d3e46b3d215587ce10cd3d8fcf3ff25e to your computer and use it in GitHub Desktop.
Save hereswhatidid/d3e46b3d215587ce10cd3d8fcf3ff25e to your computer and use it in GitHub Desktop.
Generate the image HTML with a limited srcset range of sizes
<?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