Sort Uploads Into Folders by File Type
Stores new uploads in images, videos, audio and documents folders inside your uploads directory, which keeps the file system tidy on large sites.
Opens WPIDE on
Code
$wpide_upload_type_folder = '';
add_filter( 'wp_handle_upload_prefilter', function ( $file ) use ( &$wpide_upload_type_folder ) {
$check = wp_check_filetype( isset( $file['name'] ) ? $file['name'] : '' );
$mime = (string) $check['type'];
if ( 0 === strpos( $mime, 'image/' ) ) {
$wpide_upload_type_folder = 'images';
} elseif ( 0 === strpos( $mime, 'video/' ) ) {
$wpide_upload_type_folder = 'videos';
} elseif ( 0 === strpos( $mime, 'audio/' ) ) {
$wpide_upload_type_folder = 'audio';
} else {
$wpide_upload_type_folder = 'documents';
}
return $file;
} );
add_filter( 'upload_dir', function ( $dirs ) use ( &$wpide_upload_type_folder ) {
if ( '' === $wpide_upload_type_folder || ! empty( $dirs['error'] ) ) {
return $dirs;
}
$subdir = '/' . $wpide_upload_type_folder . $dirs['subdir'];
$dirs['path'] = $dirs['basedir'] . $subdir;
$dirs['url'] = $dirs['baseurl'] . $subdir;
$dirs['subdir'] = $subdir;
return $dirs;
} );
add_filter( 'wp_handle_upload', function ( $upload ) use ( &$wpide_upload_type_folder ) {
$wpide_upload_type_folder = '';
return $upload;
} );
Notes
Only new uploads are affected; existing files stay where they are. The year and month folders are kept inside each type folder when that setting is on.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.