Search code examples
phpwordpressupload

Changing the upload path of a specific file in WordPress


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.


Solution

  • You can try the following, although I haven't tested it.

    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
             add_filter( 'upload_dir', 'pdf_upload_dir' );
        }
     
        return $file;
    }
    
    add_filter( 'wp_handle_upload_prefilter', 'custom_upload_directory' );
    
    function pdf_upload_dir($param){
        $mydir = '/test-for-pdf';
        $param['path'] = $param['basedir'] . $mydir;
        $param['url']  = $param['baseurl'] . $mydir;
        remove_filter( 'upload_dir', 'pdf_upload_dir' );
        return $param;
    }