Search code examples
javascriptjquerywordpressfile-uploaduser-input

Limit input field options JS


I am working on a Wordpress website and I have a very simple <input type="image"> through which user can send image files.

I have some very specific requests and I would like the uploaded file to be:

  • min 3000x3000 px
  • max 5000x5000 px
  • max 36MB
  • 1:1 aspect ratio

Is there a way I can set this limits via JS/jQuery?


Solution

  • To get info about image before upload use wp_handle_upload_prefilter . Aspect ratio is comparing width and height.

    function test($file) {
        $data = getimagesize($file['tmp_name']);
        error_log(print_r($data,true));
        //Returns
        // Array (
        //     [0] => 3000 // width
        //     [1] => 3000 // height
        //     [2] => 3
        //     [3] => width="3000" height="30000"
        //     [bits] => 8
        //     [mime] => image/png
        // )
        error_log(print_r($file,true));
        //returns 
        // Array (
        //     [name] => filename.png
        //     [type] => image/png
        //     [tmp_name] => /tmp/phpEJC5NR
        //     [error] => 0
        //     [size] => 4347 // file size in bits
        // )
        return $file;
    }
    add_action('wp_handle_upload_prefilter','test');