Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save giventofly/b80618316ac9543e5e6c75f2d6b13a3d to your computer and use it in GitHub Desktop.
Save giventofly/b80618316ac9543e5e6c75f2d6b13a3d to your computer and use it in GitHub Desktop.
Wordpress upload to custom folder and allow different extensions
//uploads to specific dir
//allow xml and .wer
$allowedExtensions = array('wer' => 'application/wer', 'xml' => 'application/xml');
$pathinsideuploads = '/myfiles';
add_filter('upload_mimes', 'custom_upload_files');
function custom_upload_files($mimes) {
global $allowedExtensions;
$mimes = array_merge($mimes, $allowedExtensions);
return $mimes;
}
//https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter
add_filter('wp_handle_upload_prefilter', 'my_pre_upload');
function my_pre_upload($file) {
add_filter('upload_dir', 'my_upload_dir');
return $file;
}
//https://codex.wordpress.org/Function_Reference/wp_handle_upload
add_filter('wp_handle_upload', 'my_post_upload');
function my_post_upload($fileinfo) {
remove_filter('upload_dir', 'my_upload_dir');
return $fileinfo;
}
function my_upload_dir($path){
global $pathinsideuploads;
$extension = substr(strrchr($_POST['name'],'.'),1);
if(!empty($path['error']) || ( array_key_exists($extension,$allowedExtensions))) { return $path; } //error or other filetype; do nothing.
$customdir = $pathinsideuploads;
$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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment