Home / Admin / Limit Uploaded Image Size
Duplicate Snippet

Embed Snippet on Your Site

Limit Uploaded Image Size

Set a max width and height for your image uploads to save space.

Code Preview
php
<?php
add_filter( 'wp_handle_upload', function ( $file ) {
	$max_width = 1920;
	$max_height = 1920;
	// Check if the file is an image.
	$mime_type = mime_content_type( $file['file'] );
	if ( strpos( $mime_type, 'image' ) === false ) {
		return $file;
	}
	// Get the image size.
	$image_size = getimagesize( $file['file'] );
	if ( ! $image_size ) {
		return $file;
	}
	// Check if the image is smaller than 1920px width or height.
	if ( $image_size[0] <= $max_width && $image_size[1] <= $max_height ) {
		return $file;
	}
	// Resize the image.
	$image_editor = wp_get_image_editor( $file['file'] );
	if ( is_wp_error( $image_editor ) ) {
		return $file;
	}
	$image_editor->resize( $max_width, $max_height );
	$image_editor->save( $file['file'] );
	return $file;
} );

Comments

Add a Comment