Created
April 10, 2019 17:32
-
-
Save Asikur22/205cac55479b3b26e1f55b1e305f2dcf to your computer and use it in GitHub Desktop.
[Change WordPress Upload Directory for Specific Files Types] #Media
This file contains hidden or 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
/* | |
* Change Upload Directory for Specific Files Type | |
* Only works in WordPress 3.3+ | |
*/ | |
function wpse47415_pre_upload( $file ) { | |
add_filter( 'upload_dir', 'wpse47415_custom_upload_dir' ); | |
return $file; | |
} | |
function wpse47415_post_upload( $fileinfo ) { | |
remove_filter( 'upload_dir', 'wpse47415_custom_upload_dir' ); | |
return $fileinfo; | |
} | |
function wpse47415_custom_upload_dir( $path ) { | |
$extension = substr( strrchr( $_POST[ 'name' ], '.' ), 1 ); | |
if ( empty( $path[ 'error' ] ) ) { | |
switch ( $extension ) { | |
case 'pdf': | |
$customdir = '/pdf'; | |
break; | |
case 'doc': | |
$customdir = '/doc'; | |
break; | |
case 'zip': | |
$customdir = '/zip'; | |
break; | |
} | |
} else { | |
return $path; | |
} | |
$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; | |
} | |
add_filter( 'wp_handle_upload_prefilter', 'wpse47415_pre_upload' ); | |
add_filter( 'wp_handle_upload', 'wpse47415_post_upload' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment