I'm not skilled in php, but I have found a snippet that will limit my users from uploading 'image' files to my wordpress site, that are larger than 1mb. (I'll edit this limit to suit my requirements). I'm assuming 'image' files are jpg, png, etc. But what about pdf files, will this snippet limit them too, or are they not classified as 'image' type files?
Ideally, I need to limit jpg and pdf files. Does this need modification?
// WP - LIMIT IMAGE UPLOAD SIZE
function max_image_size( $file ) {
$size = $file['size'];
$size = $size / 1024;
$type = $file['type'];
$is_image = strpos( $type, 'image' ) !== false;
$limit = 1024;
$limit_output = '1MB';
if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
return $file;
}//end max_image_size()
add_filter( 'wp_handle_upload_prefilter', 'max_image_size' );
( Using php 7.2 ) Thanks in advance, Chris.
If you want to limit all the resources replace:
if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
with:
if ( $size > $limit ) {
$file['error'] = 'Files must be smaller than ' . $limit_output;
}//end if
Optional [1]: you can rename the max_image_size function to max_file_size and change the addfilter to add_filter( 'wp_handle_upload_prefilter', 'max_file_size' );
Optional [2]: you can detect the PDF mime type, which is application/pdf by using:
$is_pdf = strpos( $type, 'pdf' ) !== false;
and add other condition:
if ( $is_image && $size > $limit ) {
$file['error'] = 'Image files must be smaller than ' . $limit_output;
}//end if
if ( $is_pdf && $size > $limit ) {
$file['error'] = 'PDF files must be smaller than ' . $limit_output;
}//end if