Change upload directory for PDF files

Following Justice Is Cheap lead, I ended adapting the functions from this plugin: http://wordpress.org/extend/plugins/custom-upload-dir/

<?php
/* 
 * Change upload directory for PDF files 
 * Only works in WordPress 3.3+
 */

add_filter('wp_handle_upload_prefilter', 'wpse47415_pre_upload');
add_filter('wp_handle_upload', 'wpse47415_post_upload');

function wpse47415_pre_upload($file){
    add_filter('upload_dir', 'wpse47415_custom_upload_dir');
    return $file;
}

function wpse47415_post_upload($fileinfo){
    remove_filter('upload_dir', 'wpse47415_custom_upload_dir');
    return $fileinfo;
}

function wpse47415_custom_upload_dir($path){    
    $extension = substr(strrchr($_POST['name'],'.'),1);
    if(!empty($path['error']) ||  $extension != 'pdf') { return $path; } //error or other filetype; do nothing. 
    $customdir="/pdf";
    $path['path']    = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
    $path['url']     = str_replace($path['subdir'], '', $path['url']);      
    $path['subdir']  = $customdir;
    $path['path']   .= $customdir; 
    $path['url']    .= $customdir;  
    return $path;
}

Leave a Comment