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' );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *