Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Forked from susanlangenes/uploads.php
Created May 29, 2021 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliffordp/c4368505752c0057b61b7e8e8885c97f to your computer and use it in GitHub Desktop.
Save cliffordp/c4368505752c0057b61b7e8e8885c97f to your computer and use it in GitHub Desktop.
// 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