Search code examples
wordpressmediafile-type

Limit filetype and wp media - wordpress


This is my input markup:

<div class="button-primary" id="fileToUpload">Upload</div>

This is js:

jQuery( '#fileToUpload' ).click( function()
{
    var custom_uploader = wp.media
    ({
        title: 'Select',
        button: {
            text: 'Select'
        },
        multiple: false  // Set this to true to allow multiple files to be selected.
    })
    .on( 'select', function()
    {
        var attachment = custom_uploader.state().get( 'selection' ).first().toJSON();
        jQuery( '#previewImage' ).attr( 'src', attachment.url );
        jQuery( '.custom_media_url' ).val( attachment.url );
        jQuery( '.custom_media_id' ).val( attachment.id );
    })
    .open();
});

I want to limit the the file type to jpg,jpeg and png. How can i achieve this?


Solution

  • You want to plug into the upload_mimes filter, like so:

    function vnm_restrictMimeTypes($mimes) {
        $mimes = array(
            'jpg|jpeg|jpe' => 'image/jpeg',
            'png' => 'image/png',
        );
    
        return $mimes;
    }
    
    add_filter('upload_mimes','vnm_restrictMimeTypes');
    

    This replaces the passed $mimes array with one limited to only the accepted image filetypes.

    Note that this doesn't stop the user from browsing for non-allowed filetypes, but when they try to upload they'll receive an error: Sorry, this file type is not permitted for security reasons.