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.
Opens WPIDE on
Code
$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 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.