Set different max upload size limits based on file type/extension

When uploading with video files to the Media Library, it's apparent that you need to increase the Max upload file size value. But this will be applied to all media types, including images and documents.

Is there any way or simple code that can set different size limits based on the file type/extension so that I can grant a large limit for videos, a small limit for images, and a different limit for documents?

I think WordPress should handle this natively because it's not logical to have the same limit for all file types. This was OK in the past when WordPress saw the light for the first time, but not in the current time.

Topic media-settings limit media-library uploads Wordpress

Category Web


This should work:

function max_video_size( $file ) {
  $size = $file['size'];
  $size = $size / 1024;
  $type = $file['type'];
  $is_image = strpos( $type, 'video' ) !== false;
  $limit = 750;
  $limit_output = '750kb';
  if ( $is_image && $size > $limit ) {
    $file['error'] = 'Video files must be smaller than ' . $limit_output;
  }
  return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'max_video_size' );

Rinse and repeat, changing video in the $is_image line to whatever filetype you want to specify, and even by altering the function, building all desired filetypes into the one filter.


FULL DISCLOSURE = the core of this answer is found in Set limit to media upload?

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.