wp_handle_upload() – how to upload to a custom subdirectory within uploads

You can work on the idea that Joost provided and use the upload_dir filter to temporarily set the upload path to somewhere else.

/**
 * Override the default upload path.
 * 
 * @param   array   $dir
 * @return  array
 */
function wpse_141088_upload_dir( $dir ) {
    return array(
        'path'   => $dir['basedir'] . '/mycustomdir',
        'url'    => $dir['baseurl'] . '/mycustomdir',
        'subdir' => '/mycustomdir',
    ) + $dir;
}

And then in practice, it’s as easy as:

// Register our path override.
add_filter( 'upload_dir', 'wpse_141088_upload_dir' );

// Do our thing. WordPress will move the file to 'uploads/mycustomdir'.
$result = wp_handle_upload( $_FILE['myfile'] );

// Set everything back to normal.
remove_filter( 'upload_dir', 'wpse_141088_upload_dir' );

Leave a Comment