-
-
Save cliffordp/c4368505752c0057b61b7e8e8885c97f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// put uploaded files into filetype based directories | |
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter'); | |
add_filter('wp_handle_upload', 'wpse_25894_handle_upload'); | |
function wpse_25894_handle_upload_prefilter( $file ) | |
{ | |
add_filter('upload_dir', 'wpse_25894_custom_upload_dir'); | |
return $file; | |
} | |
function wpse_25894_handle_upload( $fileinfo ) | |
{ | |
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir'); | |
return $fileinfo; | |
} | |
function wpse_25894_custom_upload_dir($path) | |
{ | |
// Determines if uploading from inside a post/page/cpt | |
// If not, default Upload folder is used | |
$use_default_dir = ( | |
isset($_REQUEST['post_id'] ) | |
&& $_REQUEST['post_id'] == 0 | |
) | |
? true : false; | |
if( !empty( $path['error'] ) || $use_default_dir ) | |
return $path; //error or uploading not from a post/page/cpt | |
// Save uploads in FILETYPE based folders. When using this method, | |
// you may want to change the check for $use_default_dir | |
$extension = substr( strrchr( $_POST['name'], '.' ), 1 ); | |
switch( $extension ) | |
{ | |
case 'jpg': | |
case 'jpeg': | |
case 'png': | |
case 'gif': | |
$customdir = '/images'; | |
break; | |
case 'mp4': | |
case 'm4v': | |
$customdir = '/video'; | |
break; | |
case 'mp3': | |
$customdir = '/audio'; | |
break; | |
case 'txt': | |
case 'doc': | |
case 'pdf': | |
$customdir = '/documents'; | |
break; | |
default: | |
$customdir = '/otherfiles'; | |
break; | |
} | |
//remove default subdir (year/month) | |
$path['path'] = str_replace($path['subdir'], '', $path['path']); | |
$path['url'] = str_replace($path['subdir'], '', $path['url']); | |
$path['subdir'] = $customdir; | |
$path['path'] .= $customdir; | |
$path['url'] .= $customdir; | |
return $path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment