# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Media](https://wpide.com/library/category/media/)
- Tags: uploads, folders, organization
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/upload-folders-by-file-type/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Sort Uploads Into Folders by File Type" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
