wp_handle_upload() works for me, but uploads files where it wants (uploads/year/month).

Question: Is there any way to tell it to upload files to a custom dir (uploads/mycustomdir)? Or is there some other function which could do this?

What I tried:

  1. php's move_uploaded_file() (wasn't able to figure the target directory parameter - this is for a plugin and I need it to work for everyone regardless of their dir structure).

  2. https://yoast.com/smarter-upload-handling-wp-plugins

I pasted this code into my plugin's core file. Nothing happened. But I see in the comments this seems to work for people.

PLEASE if you have an answer, give a complete one. I'm able to get $_FILES['myfile']. What steps to take from there to make that file go to uploads/mycustomfolder?

1 Answer 1


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' );
  • Thanks a lot for guidance. This almost works, but now I'm getting: "Unable to create directory wp-content/uploads/mycustomdir. Is its parent directory writable by the server?". To me, seems obvious that parent directory is writable by the server, as uploads there work just fine. Apr 12, 2014 at 11:02
  • Trying to solve above problem, I tried creating mycustomdir on plugin activation, using this snippet: wpmayor.com/… Result: on my localhost it works (and so does your code) - but on production server it says: "The plugin generated 233 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin." Apr 12, 2014 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.