How to set file type in wp_handle_upload?

I’m using wp_handle_upload to allow users upload .csv files in the front end and it’s working fine. I was wondering how can I limit this to only allow .csv files though since currently it accepts a wide variety of file types. According to the doc this should be possible by overriding the $overrides param but I’m not sure what should I pass it to do so.

Thanks in advance!

Related posts

Leave a Reply

2 comments

  1. Got it, looking at the source code I came up with this:

    wp_handle_upload($file_input, array('test_form' => false, 'mimes' => array('csv' => 'text/csv')));
    

    To override the mime types just pass mimes as an array wit the key being the file extension and the value as the mime type.

  2. The filter you’ll want to use is ‘upload_mimes’ http://xref.yoast.com/trunk/_functions/get_allowed_mime_types.html

    The function get_allowed_mime_types gets the filtered $mimes array, so if you want to ONLY allow csv uploads, you can do this:

    add_filter('upload_mimes', 'javiervd_filter_mime_types');
    function javiervd_filter_mime_types($mimes)
    {
      return array('csv' => 'text/csv');
    }
    

    Normally with a filter, you’d want to alter the input and return it, but since you only want .csv uploads, you can simply return an array with the one element. It’s important to note this will override permitted upload types across the site.

    UPDATE: Ok, here’s what you can do. I’m assuming the user is logged out, and that’s a good way to test that this is the kind of upload where only csvs are permitted. If it’s not, you can always just modify your if check and make sure the filter only gets applied to front-end uploads.

    add_filter('wp_handle_upload_prefilter' 'javiervd_maybe_filter_mimes');
    function javiervd_maybe_filter_mimes($file)
    {
      //if not logged in, limit uploads to csvs
      if(!is_user_logged_in())
      { 
         add_filter('upload_mimes', 'javiervd_filter_mime_types');   
         //add another filter to remove the mime filter so it only applies for the one function call
         add_filter('wp_handle_upload', 'javierd_remove_mime_filter');
      }
    }
    
    function javiervd_filter_mime_types($mimes)
    {
      return array('csv' => 'text/csv');
    }   
    
    function javiervd_remove_mime_filter($upload)
    {
      remove_filter('upload_mimes', 'javiervd_filter_mime_types');
      return $upload;
    }