Reject upload of wrong-sized images using the Media Uploader

I’m working on a super-strict setting for adding images to Custom Fields in the Post Edit screen. My optimal scenario would be to add a a Custom Error message when the user tries to upload an image of the wrong size for that specific custom value.

I’m aware I can do this with any custom uploader, but I’d really prefer to do it with the regular Media Uploader. I’m also aware of the wp_handle_upload_prefilter which I already use to validate filenames and generate custom error messages based on generic requirements. What I need right now is a way to use custom requirements to reject uploads based on which field we’re uploading to.

I’m also aware of Differentiate Featured Image from Post Images upon Upload but I wanted a pre-save solution.

This would look something like this:

enter image description here

Any ideas on how to go about informing wp_handle_upload_prefilter ( or a similar ) of which field we’re dealing with?

1

In your handler, if you set ‘error’, the error message will be displayed and will cancel the upload

add_filter( 'wp_handle_upload_prefilter', 'custom_upload_filter' );

function custom_upload_filter( $file ) {
    $image_info   = getimagesize( $file['tmp_name'] );
    $image_width  = $image_info[0];
    $image_height = $image_info[1];

    if ( $image_with !== 800 || $image_height !== 600 ) {
        $file['error'] = __( 'Images must be sized exactly 800 * 600', 'your_textdomain' );
    }
    return $file;
}

If your user attempts to upload a different size, the message will be:

“thefile.png” has failed to upload due to an error  
Size must be exactly 800 * 600

Note that wp_handle_upload_prefilter comes very early in upload processing, so you may want to test if the file has been properly uploaded (from HTTP standpoint) and is an image before testing the size.

Ref: funtion wp_handle_upload() in the core file wp-admin/includes/file.php

Leave a Comment