Written on 13. December 2021 by Lennart Christensen

Limit upload Image Size to WordPress Media Library

function cco_limit_image_size($file) {
		$image_size = $file['size']/1024; // Calculate the image size in KB (1024kb = 1mb)
	$limit = 1024 * 3; // File size limit in KB * (1024kb = 1mb = limit to 3mb)
	$is_image = strpos($file['type'], 'image'); // Check if it's an image
	if ( ( $image_size > $limit ) && ($is_image !== false) )
		$file['error'] = sprintf( __( 'Image files must be smaller than %sKB (%sMB)','cco'), $limit, $limit/1024);
	return $file;
}
add_filter('wp_handle_upload_prefilter', 'cco_limit_image_size');

The function prevents you from uploading images larger than the limit to the media library. WordPress rejects the image with an error message. The code snippet must be placed in functions.php.

Do you also want to restrict pdf and video files? Here a function with PDF and video media types included:

function cco_limit_image_size($file) {
		$file_size = $file['size']/1024; // Calculate the image size in KB (1024kb = 1mb)
	$is_image[] = ['type' => 'image', 'limit' => 3]; // Check if it's an image
	$is_document[]   = ['type' => 'pdf', 'limit' => 3]; // Check if it's an PDF
	$is_video[] = ['type' => 'video', 'limit' => 10]; // Check if it's an Video
	$types = array_merge($is_image, $is_document,  $is_video);
	foreach ($types as $type) {
		$limit = 1024 * $type['limit']; // File size limit in KB * (1024kb = 1mb)
		if ( ( $file_size > $limit ) && (strpos($file['type'], $type['type']) !== false) ) {
			$file['error'] = sprintf( __( '%s files must be smaller than %sKB (%sMB)', 'cco' ), $type['type'], $limit, $limit / 1024 );
		}
	}
	return $file;
}
add_filter('wp_handle_upload_prefilter', 'cco_limit_image_size');