Halloween Sale 15% off Ends in See the plans
PHP

Store Each User's Uploads in Their Own Folder

Saves uploads into a folder named after the uploader, such as uploads/users/jane/2025/03/, which keeps multi-author and client sites tidy and makes per-person cleanups easy.

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

Code

$wpide_user_folder = function ( $dirs ) {
    $user = wp_get_current_user();
    if ( ! $user->exists() ) {
        return $dirs;
    }

    $folder = '/users/' . sanitize_file_name( $user->user_nicename );
    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_user_folder_on = function ( $file ) use ( $wpide_user_folder ) {
    add_filter( 'upload_dir', $wpide_user_folder );
    return $file;
};
$wpide_user_folder_off = function ( $upload ) use ( $wpide_user_folder ) {
    remove_filter( 'upload_dir', $wpide_user_folder );
    return $upload;
};
add_filter( 'wp_handle_upload_prefilter', $wpide_user_folder_on );
add_filter( 'wp_handle_sideload_prefilter', $wpide_user_folder_on );
add_filter( 'wp_handle_upload', $wpide_user_folder_off );
add_filter( 'wp_handle_sideload', $wpide_user_folder_off );

Notes

Only affects new uploads; existing files stay where they are. Uses the user's nicename, never their email.

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.