Skip to content

Instantly share code, notes, and snippets.

@blainerobison
Last active August 24, 2022 00:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save blainerobison/e802658da007e6e806b1 to your computer and use it in GitHub Desktop.
Save blainerobison/e802658da007e6e806b1 to your computer and use it in GitHub Desktop.
wp: Custom Upload Directory By File Type [WordPress]
/**
* Set custom upload directory
*
* Images => /img
* PDF => /pdf
* Misc => /misc
*
* Note: Doesn't work with 'browser uploader'
* Note: Use with 'wp_update_attachment_metadata' hook if we want to define our own attachment metadata
* Allowed file types: http://codex.wordpress.org/Uploading_Files#About_Uploading_Files_on_Dashboard
*/
function prefix_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 ) ) :
// PDF
$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', 'prefix_pre_upload', 0 );
add_filter( 'wp_handle_upload', 'prefix_post_upload', 0 );
/**
* Add custom directory filter
*
* 'prefix_custom_upload_directory'
*/
function prefix_pre_upload( $file ) {
add_filter( 'upload_dir', 'prefix_custom_upload_directory' );
return $file;
}
/**
* Remove custom directory filter
*
* 'prefix_custom_upload_directory'
*/
function prefix_post_upload( $fileinfo ) {
remove_filter( 'upload_dir', 'prefix_custom_upload_directory' );
return $fileinfo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment