Skip to content

Instantly share code, notes, and snippets.

@graylaurenm
Created February 26, 2018 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graylaurenm/73ceec9a60bd77cfbd903a2aa325eb2d to your computer and use it in GitHub Desktop.
Save graylaurenm/73ceec9a60bd77cfbd903a2aa325eb2d to your computer and use it in GitHub Desktop.
Cool things we can do with srcset in themes...
<?php
/**
* When using thumbnails, anything using the chosen
* thumbnail size should adjust their srcset sizes to
* match. This assumes image sizes are always precise and
* used in the same layouts/collapse.
*
* In this case, the chosen image is 222px wide on larger
* screens and about 29-31% of the viewport on smaller.
* We used the upper limit for simplity.
*
* @since 1.0.0
*
* @author Lauren Gray <lauren@oncecoupled.com>
*
* @param array $attr Attributes for the image markup
* @param WP_Post $attachment Image attachment post
* @param string|array $size Requested size
*
* @return array New attributes to use
*/
add_filter( 'wp_get_attachment_image_attributes', __NAMESPACE__ . '\thumbnail_srcset', 10 , 3 );
function thumbnail_srcset( $attr, $attachment, $size ) {
if ( $size === 'third-portrait' ) {
$attr['sizes'] = '(min-width: 1024px) 222px, 31vw';
}
return $attr;
}
/**
* For in-content images, use the content width on larger
* screens, then a portion of the viewport on smaller.
*
* In this case, our content width is 700px on larger
* screens and about 93-96% of the viewport on smaller.
* We used the upper limit for simplicity.
*
* @since 1.0.0
*
* @author Lauren Gray <lauren@oncecoupled.com>
*
* @param array|string $size Image size to retrieve
*
* @return array|string New size
*/
add_filter( 'wp_calculate_image_sizes', __NAMESPACE__ . '\content_image_srcset', 10 , 2 );
function content_image_srcset( $size ) {
$width = $size[0];
return '(min-width: 1024px) 700px, 96vw';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment