Wordpress - 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;
}

By default, WordPress blocks .csv file uploads. The mime_types filter will allow you to add .csv files or any other file to be uploaded:

add_filter( 'mime_types', 'wpse_mime_types' );
function wpse_mime_types( $existing_mimes ) {
    // Add csv to the list of allowed mime types
    $existing_mimes['csv'] = 'text/csv';

    return $existing_mimes;
}

If you want a temporary quick and easy solution you can allow unfiltered uploads in your wp-config.php .

define('ALLOW_UNFILTERED_UPLOADS', true);

This line should probably not stay in your config.php, but if you want to do something like a woocommerce products import via CSV only once, it can be an easy fix.

Tags:

Csv

Uploads