Created
March 11, 2015 00:32
-
-
Save blainerobison/552e49abec345d431dd3 to your computer and use it in GitHub Desktop.
Custom Upload Directories
This file contains 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
/** | |
* Add custom directory filter | |
* | |
* 'ev_custom_upload_directory' | |
*/ | |
function ev_pre_upload( $file ) { | |
add_filter( 'upload_dir', 'ev_custom_upload_directory' ); | |
return $file; | |
} | |
/** | |
* Remove custom directory filter | |
* | |
* 'ev_custom_upload_directory' | |
*/ | |
function ev_post_upload( $fileinfo ) { | |
remove_filter( 'upload_dir', 'ev_custom_upload_directory' ); | |
return $fileinfo; | |
} | |
/** | |
* Set custom upload directory | |
* | |
* Images => /img | |
* PDF => /pdf | |
* Misc => /misc | |
* | |
* Note: Doesn't work with 'browser uploader' | |
* Allowed file types: http://codex.wordpress.org/Uploading_Files#About_Uploading_Files_on_Dashboard | |
*/ | |
function ev_custom_upload_directory( $upload ) { | |
$file_type = array(); | |
// Get file type | |
if( ! empty( $_POST['name'] ) ) : | |
$custom_directory = ''; | |
$file_type = wp_check_filetype( $_POST['name'] ); | |
$file_ext = ( $file_type['ext'] ) ? $file_type['ext'] : ''; | |
// set directory based on file type | |
if( in_array( strtolower( $file_ext ), array( 'jpg', 'jpeg', 'png', 'gif' ) ) ) : | |
// Images | |
$custom_directory = '/img'; | |
elseif( 'pdf' === strtolower( $file_ext ) ) : | |
$custom_directory = '/pdf'; | |
else: | |
// Misc | |
$custom_directory = '/misc'; | |
endif; | |
// update directory | |
if( $custom_directory ) : | |
// remove default subdir (year/month) | |
$upload['path'] = str_replace( $upload['subdir'], '', $upload['path'] ); | |
$upload['url'] = str_replace( $upload['subdir'], '', $upload['url'] ); | |
// update paths | |
$upload['subdir'] = $custom_directory; | |
$upload['path'] .= $custom_directory; | |
$upload['url'] .= $custom_directory; | |
endif; | |
endif; | |
return $upload; | |
} | |
add_filter( 'wp_handle_upload_prefilter', 'ev_pre_upload' ); | |
add_filter( 'wp_handle_upload', 'ev_post_upload' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment