skip to Main Content

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


  1. 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/

    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search