Search code examples
wordpressresponsive-images

Wordpress - Responsive images - remove sizes


Sometime ago I added a couple of additional image formats to Wordpress in order to fine-tune my responsive display. I added those lines to functions.php:

add_image_size( "maximal", "1900" );
add_image_size( "desktop", "1400" );
add_image_size( "tablet", "900" );
add_image_size( "smalltablet", "700" );
add_image_size( "mobile", "500" );
add_theme_support( 'post-thumbnails' ); 

I release I was too greedy because I'm not using most of those formats now and I would like to remove some of them. To do so I basically commented the image formats that I wanted to get rid of but from what I see, all srcset attributes are still listing them in my code.

Is there a way to tell Wordpress to stop adding those formats in srcset ? I thought of using a regex to get rid of them but that generates additional processing to the page.

Thanks

Laurent


Solution

  • To make sure that these images' sizes is unregistered use this:

    remove_image_size( "maximal" );
    

    Then use these filters to clean the current images from these sizes:

    // Remove the calculated image sizes
    add_filter( 'wp_calculate_image_sizes', '__return_false' );
    
    // Remove the calculated image sizes
    add_filter( 'wp_calculate_image_srcset', '__return_false' );
    
    // Clean image attrs
    add_filter( 'wp_get_attachment_image_attributes', 'unset_image_sizes');
    function unset_image_sizes() {
      if( isset( $attr['sizes'] ) )
        unset( $attr['sizes'] );
    
      if( isset( $attr['srcset'] ) )
        unset( $attr['srcset'] );
    }
    

    I hope this helps.