# Store Uploads in Folders Named After the Post Type

> Saves files uploaded from inside a post, page or custom post into a folder named after its type, such as uploads/products/ or uploads/pages/, keeping the year and month folders inside.

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

## Code

```php
$wpide_post_type_folder = function ( $dirs ) {
    $post_id = isset( $_REQUEST['post_id'] ) ? absint( $_REQUEST['post_id'] ) : ( isset( $_REQUEST['post'] ) ? absint( $_REQUEST['post'] ) : 0 );
    if ( ! $post_id ) {
        return $dirs;
    }

    $type = get_post_type( $post_id );
    if ( ! $type || 'attachment' === $type ) {
        return $dirs;
    }

    $folder = '/' . sanitize_title( get_post_type_object( $type )->labels->name );
    if ( 0 === strpos( $dirs['subdir'], $folder ) ) {
        return $dirs;
    }

    $dirs['subdir'] = $folder . $dirs['subdir'];
    $dirs['path']   = $dirs['basedir'] . $dirs['subdir'];
    $dirs['url']    = $dirs['baseurl'] . $dirs['subdir'];

    return $dirs;
};

// Only change the folder while a file is being uploaded.
$wpide_folder_on = function ( $file ) use ( $wpide_post_type_folder ) {
    add_filter( 'upload_dir', $wpide_post_type_folder );
    return $file;
};
$wpide_folder_off = function ( $upload ) use ( $wpide_post_type_folder ) {
    remove_filter( 'upload_dir', $wpide_post_type_folder );
    return $upload;
};
add_filter( 'wp_handle_upload_prefilter', $wpide_folder_on );
add_filter( 'wp_handle_sideload_prefilter', $wpide_folder_on );
add_filter( 'wp_handle_upload', $wpide_folder_off );
add_filter( 'wp_handle_sideload', $wpide_folder_off );
```

## Notes

Only affects new uploads made from the editor; files uploaded directly to the Media Library keep the default folders.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Store Uploads in Folders Named After the Post 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/
