I want every time I upload a PDF file to my site, instead of the default WordPress path, my file will be saved in a different path.
For this purpose, I have placed the following filter in the functions.php
file:
function custom_upload_directory( $file ) {
// Check if the file is a PDF
if ( $file['type'] == 'application/pdf' ) {
// Set the upload directory to a custom location
$file['url'] = '/wp-content/uploads/test-for-pdf/' . $file['name'];
$file['error'] = false;
}
return $file;
}
add_filter( 'wp_handle_upload_prefilter', 'custom_upload_directory' );
By placing this filter, the PDF file is uploaded correctly in WordPress, but it is saved in its default path and no file is uploaded in the path I want.
2
Answers
From my reading of the wp_handle_upload_prefilter page on WP (which I don’t use) you don’t get the option to change the path in that filter, only the name.
The default location is defined during bootstrap, and I’d advise not screwing with it. Instead use a plugin, or write a cron script to move the files.
See: https://devowl.io/knowledge-base/real-physical-media-change-wp-content-uploads-folder/
You can try the following, although I haven’t tested it.