How to set an upload directory for each media type?

[More info added]. See below the code.

//~ change upload dir
add_filter('upload_dir', 'choose_upload_dir');

//~ upload image
$upload = wp_handle_upload( $_FILES['your_form_input_name'], array('test_form' => false) );

//~ change upload dir back
remove_filter('upload_dir', 'choose_upload_dir');

function choose_upload_dir($upload) {
    //~ your file to upload
    $file_type = $_FILES['your_form_input_name']['type'];

    //~ switch between file types
    switch($file_type) {
        //~ if type is 'png' then upload subdir is '/png' and so on
        case 'image/png':
            $type_dir="/png";
        break;

        case 'image/jpeg':
            $type_dir="/jpg";
        break;

        default:
            $type_dir="/others";
    }

    $upload['subdir'] = $upload['subdir'].$type_dir;
    $upload['path'] = $upload['basedir'].$upload['subdir'];
    $upload['url'] = $upload['baseurl'].$upload['subdir'];

    return $upload;
}
?>

More info: Casually I’ve stumbled upon useful plugin which allows you to setup different directories for your uploads: Relocate Upload

Leave a Comment