Last active
          May 8, 2023 02:56 
        
      - 
      
- 
        Save BruceMcKinnon/2cbb82b130af8bf196aa730b1654ef13 to your computer and use it in GitHub Desktop. 
    Filter the Wordpress srcset to ensure the browser isn't given an image it needs to upscale.
  
        
  
    
      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
    
  
  
    
  | // | |
| // Filter the WP srcset to ensure the browser isn't given a file it needs to upscale. | |
| // | |
| add_filter( 'wp_calculate_image_srcset_meta','ingeni_srcset_filter', 4, 10); | |
| function ingeni_srcset_filter($image_meta, $size_array, string $image_src, int $attachment_id ) { | |
| // We'll allow images within 2% of the required width or height. | |
| $min_width = ($size_array[0] * 0.98); | |
| $min_height = ($size_array[1] * 0.98); | |
| $deleted_count = 0; | |
| $size_count = count($image_meta['sizes']); | |
| $keys = array_keys($image_meta['sizes']); | |
| if ( $size_count > 2 ) { | |
| for ( $idx = ($size_count-1); $idx >= 0; $idx-- ) { | |
| if ( ( $image_meta['sizes'][$keys[$idx]]['width'] < $min_width ) || ( $image_meta['sizes'][$keys[$idx]]['height'] < $min_height ) ) { | |
| if ( $size_count > $deleted_count ) { | |
| unset($image_meta['sizes'][$keys[$idx]]); | |
| $deleted_count++; | |
| } | |
| } | |
| } | |
| } | |
| return $image_meta; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment