Skip to content

Instantly share code, notes, and snippets.

@unfulvio
Created July 9, 2014 08:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unfulvio/1ee103a6f86893771b5a to your computer and use it in GitHub Desktop.
Save unfulvio/1ee103a6f86893771b5a to your computer and use it in GitHub Desktop.
Limit WordPress media uploader maximum upload file size
<?php
/**
* Limit WordPress media uploader maximum upload file size
* Uploading very large images is pointless as they will hardly ever be used at full size.
* Crunching larger files takes more memory; larger files take more space too.
*
* @param mixed $file the uploaded file item to filter
*
* @return array $file the filtered file item with response
*/
function limit_upload_file_size( $file ) {
$images = 1024; // size in KB (example)
$others = 2048; // sizee in KB (example)
// exclude admins
if ( ! current_user_can( 'manage_options' ) ) :
// get filesize of upload
$size = $file['size'];
$size = $size / 1024; // Calculate down to KB
// get imagetype of upload
$type = $file['type'];
$is_image = strpos( $type, 'image' );
// set sizelimit in kB
$image_limit = $images;
$others_limit = $others;
if ( $is_image == true && $size > $image_limit ) {
$file['error'] = sprintf( __( 'WARNING: You should not upload images larger than %d KB. Please reduce the image file size and try again.' ), $images );
} elseif ( $is_image == false && $size > $others_limit ) {
$file['error'] = sprintf( __( 'WARNING: You should not upload files larger than %d KB. Please reduce the file size and try again.' ), $others );
}
endif;
return $file;
}
add_filter ( 'wp_handle_upload_prefilter', 'limit_upload_file_size', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment