I've found lots of tutorials on how to create a metabox file uploader using wordpress' native file uploader. However, I would like to have the uploaded file placed in to a custom directory, and I'm having a hard time finding any info on it.

Can anyone provide some leads? Thanks in advance!


I will not follow the whole metabox thing, but Just to point some " leads " as you asked regarding the upload folder ..

The upload dir in wordpress is set via the wp_upload_dir() function - which is filterable ..

$uploads = apply_filters( 'upload_dir',
    'path'    => $dir,
    'url'     => $url,
    'subdir'  => $subdir,
    'basedir' => $basedir,
    'baseurl' => $baseurl,
    'error'   => false,
) );

It is later used by the media_sideload_image , that uses wp_handle_upload - which are probably the ones you saw in those tutorials ...

so, applying a filter is trivial as :

add_filter( 'upload_dir', 'my_custom_upload_dir_function' );

Mind you , that the array parts must be constructed and supplied by you ..

you can also change the upload dir like so, on the go inside the custom function :

$wp_upload_dir =  wp_upload_dir();
$my_sur = "_my_sufrfix";
$my_new_folder = $wp_upload_dir . $my_sur ;

now, you can use $my_new_folder with wp_mkdir_p()

wp_mkdir_p( $my_new_folder );

You will need permissions for that of course ..

chmod( $my_new_folder, 0644);

The other approach, which I sometimes use is simply to apply some non-wp related functions like copy() , rename() and unlink()..

$path_parts = pathinfo($file); // we need to know the details ..
// 'dirname :: ' .  $path_parts['dirname'] . "\n";
// 'basename :: ' .  $path_parts['basename']. "\n";
// 'extension :: ' .  $path_parts['extension'] . "\n";
// 'filename :: ' .  $path_parts['filename'] . "\n"; // since PHP 5.2.0

    // $renamed_dest_path need to be constructed , can be done 
    // manually or with wp_upload_dir()
    if (!copy($file , $renamed_dest_path)) { 
        $debugtext .= "2 : failed to rename  $dest_path_2...\n";

Finally, if you want , you can @unlink the original file...

There are cons and pros to this second approach, which I will not detail now . I would assume that the first approach would be better for "normal" use in wp - but the second is very valuable for specific situations ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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