Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Plugin Name: Upload Sieve
- * Plugin URI: http://a2.gs
- * Description: Place Uploaded Files in directory by type rather than yr/mo.
- * Author: Your Name
- * Author URI: http://a2.gs
- * Version: 0.1.0
- */
- /**
- * Set custom upload directory
- *
- * Images => /img
- * PDF => /pdf
- * Misc => /misc
- *
- * Note: Doesn't work with 'browser uploader'-files will end up in the desirted location with a broken reference in the media library
- * 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;
- }
- /* Place custom code above this line. */
- ?>
Advertisement
Add Comment
Please, Sign In to add comment