Created
February 26, 2018 18:21
-
-
Save graylaurenm/73ceec9a60bd77cfbd903a2aa325eb2d to your computer and use it in GitHub Desktop.
Cool things we can do with srcset in themes...
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 | |
/** | |
* 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