Stop generating additional image sizes in WordPress

When a image added to media library, WordPress will generate 6 default image sizes and store them separately.

Then theme and plugins might generate some additional image sizes. In my case total of 13 additional image sizes were created. ?

It’s actually good to have additional image sizes to show proper image sizes based on the page or elements butt I did not need them, all I needed was the actual uploaded image.

I searched Google but none of them had any proper way to stop generating them, thus I wrote one.

/**
 * Remove the default image sizes.
 */
add_filter( 'intermediate_image_sizes_advanced', function( $sizes ) {
    unset( $sizes['thumbnail'] );
    unset( $sizes['medium'] );
    unset( $sizes['large'] );
    
    return $sizes;
});

/**
 * Remove any other image sizes generated by themes or plugins
 * Uses 'wp_loaded' hook which is fired when everything fully loaded and instantiated.
 */
add_action( 'wp_loaded', function() {
    foreach ( get_intermediate_image_sizes() as $image_sizes ) {
        remove_image_size( $image_sizes );
    }
});

Removing image size this way is completely safe. If WordPress can’t find any specific image sizes then it will automatically fallback to original.