Media PHP Intermediate

Reject Images That Are Too Small or Too Large

Block image uploads below 600 px wide or above 6000 px on either side, with a clear message explaining why.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 20 lines
add_filter( 'wp_handle_upload_prefilter', function ( array $file ): array {
	if ( ! str_starts_with( (string) ( $file['type'] ?? '' ), 'image/' ) || 'image/svg+xml' === $file['type'] ) {
		return $file;
	}

	$size = @getimagesize( $file['tmp_name'] );
	if ( ! $size ) {
		return $file;
	}

	[ $width, $height ] = $size;

	if ( $width < 600 ) {
		$file['error'] = sprintf( 'This image is %d px wide. Please upload one at least 600 px wide.', $width );
	} elseif ( $width > 6000 || $height > 6000 ) {
		$file['error'] = sprintf( 'This image is %d × %d px. Please resize it to 6000 px or less on each side.', $width, $height );
	}

	return $file;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Tiny images look blurry when your theme stretches them, and huge camera originals can run the server out of memory while WordPress creates thumbnails. This snippet stops both at upload time.

How it works

wp_handle_upload_prefilter runs before an uploaded file is saved. For images, the snippet reads the width and height with getimagesize(). If they’re outside your limits, it sets $file['error'], and WordPress shows that message in the uploader and refuses the file.

SVGs and files that aren’t images are skipped.

Things to watch

  • Change 600 and 6000 to suit your theme.
  • Applies to everyone, including administrators. Add current_user_can( 'manage_options' ) to the first check to let admins upload anything.

How to test it

Upload an image 400 px wide. You should see the “at least 600 px wide” message and the file shouldn’t be added.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only