Half Baked Idea: Limiting WordPress Image Upload Sizes

If you want to be able to limit images (or any attachments) from being uploaded into the media library if they are too large, you can use the wp_handle_upload_prefilter filter to do this.

Below is a really basic example I whipped up in a few minutes that I shared with a customer not too long ago:

/**
 * Limits the maximum size of images that can be uploaded.
 *
 * @param array $file {
 *     Reference to a single element from `$_FILES`.
 *
 *     @type string $name     The original name of the file on the client machine.
 *     @type string $type     The mime type of the file, if the browser provided this information.
 *     @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
 *     @type int    $size     The size, in bytes, of the uploaded file.
 *     @type int    $error    The error code associated with this file upload.
 * }
 *
 * @return array       Filtered file array, with a possible error if the file is too large.
 */
function blarg_limit_max_image_upload_size( $file ) {
    if ( str_starts_with( $file['type'], 'image/' ) ) {
        $max_size = 1 * 1024; // 1kb.

        if ( $file['size'] > $max_size ) {
            // translators: %s: Human readable maximum image file size.
            $file['error'] .= sprintf( __( 'Uploaded images must be smaller than %s.' ), size_format( $max_size ) );
        }
    }

    return $file;

}
add_filter( 'wp_handle_upload_prefilter', 'blarg_limit_max_image_upload_size', 10, 1 );Code language: PHP (php)

Good luck if you use any of my hot garbage in production 😀

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.