Allow CSV files to be uploaded

There’s a bug in WordPress 4.7-4.7.3 related to validating MIME types, so the code provided by Dave Romsey won’t work.

There’s a plugin in the repo that will bypass MIME checks, but it disables the checks for all users and all extensions. I think a better way would be to add a new capability for administrators that will allow them to upload .csv extensions.

//* Register activation and deactivation hooks
register_activation_hook( __FILE__ , 'wpse_258192_activation' );
register_deactivation_hook( __FILE__ , 'wpse_258192_deactivation' );

//* Add upload_csv capability to administrator role
function wpse_258192_activation() {
  $admin = get_role( 'administrator' );
  $admin->add_cap( 'upload_csv' );
}

//* Remove upload_csv capability from administrator role
function wpse_258192_deactivation() {
  $admin = get_role( 'administrator' );
  $admin->remove_cap( 'upload_csv' );
}

//* Add filter to check filetype and extension
add_filter( 'wp_check_filetype_and_ext', 'wpse_258192_check_filetype_and_ext', 10, 4 );

//* If the current user can upload_csv and the file extension is csv, override arguments - edit - "$pathinfo" changed to "pathinfo"
function wpse_258192_check_filetype_and_ext( $args, $file, $filename, $mimes ) {
  if( current_user_can( 'upload_csv' ) && 'csv' === pathinfo( $filename )[ 'extension' ] ){
    $args = array(
      'ext'             => 'csv',
      'type'            => 'text/csv',
      'proper_filename' => $filename,
    );
  }
  return $args;
}

Leave a Comment