search ]

Limit Image Upload Size in WordPress

There are situations where you want to limit content editors from uploading images beyond a certain size. You can even be more specific and allow uploads of a specific pixel size. Add the following code to your functions.php file:

/* 
 * Check image resolution (px) before crunching
 */
function savvy_validate_image_size( $file ) {
    $image = getimagesize($file['tmp_name']);
    $minimum = array(
        'width' => '460',
        'height' => '460'
    );
    $maximum = array(
        'width' => '1280',
        'height' => '1280'
    );
    $image_width = $image[0];
    $image_height = $image[1];

    $too_small = "Image dimensions are too small. Minimum size is {$minimum['width']} by {$minimum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";
    $too_large = "Image dimensions are too large. Maximum size is {$maximum['width']} by {$maximum['height']} pixels. Uploaded image is $image_width by $image_height pixels.";

    if ( $image_width < $minimum['width'] || $image_height < $minimum['height'] ) {
        $file['error'] = $too_small;
        return $file;
    }
    elseif ( $image_width > $maximum['width'] || $image_height > $maximum['height'] ) {
        $file['error'] = $too_large;
        return $file;
    }
    else
        return $file;
}
add_filter('wp_handle_upload_prefilter','savvy_validate_image_size');

You can change the minimum and maximum width and height (pixels) on lines 6-12. Take a look at the broader post on image sizes in WordPress.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo