Last active
September 2, 2020 02:52
-
-
Save blogjunkie/e676fc8c078ae9a521f8c00f58f89c4c to your computer and use it in GitHub Desktop.
Remove sources (thumbnails) from the srcset array
This file contains hidden or 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 | |
| add_filter( 'wp_calculate_image_srcset', 'child_hero_image_srcset', 10, 5 ); | |
| /** | |
| * Remove sources from the srcset array | |
| * Only use large and above | |
| * | |
| * @link https://www.smashingmagazine.com/2016/09/responsive-images-in-wordpress-with-art-direction/ | |
| */ | |
| function child_hero_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) { | |
| /* | |
| Original srcset | |
| image-300x188.jpg 300w, | |
| image-768x480.jpg 768w, | |
| image-1024x640.jpg 1024w, | |
| image-1536x960.jpg 1536w, | |
| image-2048x1280.jpg 2048w, | |
| image.jpg 2560w | |
| */ | |
| if ( is_front_page() && ( $attachment_id == '57664' ) ) { | |
| // get cutoff as width of the largest cropped image size | |
| // (in HTML, breakpoint = cutoff + 1 ) | |
| $cutoff = $image_meta['sizes']['medium_large']['width']; | |
| // check if our version is the full-sized version by | |
| // comparing its width to the cutoff | |
| if ( $cutoff < $size_array[0] ) { | |
| // for each element in tentative srcset | |
| foreach ( $sources as $key => $value ) { | |
| // if image width is at or below cutoff, | |
| // we don't need it | |
| if ( $cutoff >= $key ) { | |
| unset( $sources[ $key ] ); | |
| } | |
| } | |
| } | |
| } | |
| return $sources; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment