Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.