skip to Main Content

as we all know since WordPress 4.4 there are responsive images sizes. My goal is to remove 2 sizes from generation and even from displaying in the srcset of the images. For some reason even after using the following code, the 2 sizes still displayed in the srcset! Any solutions maybe? 🙂

add_action( 'init', 'j0e_remove_large_image_sizes' );
function j0e_remove_large_image_sizes() {
  remove_image_size( '1536x1536' );             // 2 x Medium Large (1536 x 1536)
  remove_image_size( '2048x2048' );             // 2 x Large (2048 x 2048)
}

function remove_default_image_sizes( $sizes) {
unset( $sizes['1536×1536']);
unset( $sizes['2048×2048']);
return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');

2

Answers


  1. The intermediate_image_sizes_advanced will work, but it looks like you’ve set the wrong keys there. The × is the wrong character.

    The following should work fine:

    add_filter( 'intermediate_image_sizes_advanced', function( $new_sizes, $image_meta, $attachment_id ) {
        unset( $new_sizes['1536x1536'] );
        unset( $new_sizes['2048x2048'] );
        return $new_sizes;
    }, 10, 3 );
    
    Login or Signup to reply.
  2. hook into wp_calculate_image_srcset in wp-includes/media.php:1061-1180; read detailed explanation
    $sources is an array that holds all available sizes for the srcset attribute. You can unset undesired sizes as shown below.

    add_filter( 'wp_calculate_image_srcset', 'my_custom_image_srcset', 10, 5);
    
    function my_custom_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {
        $remove = ['1536', '2048'];
        $sources = array_diff_key($sources, array_flip($remove));
        //check result with print_r
        //print_r($sources);
        return $sources;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search