I need to filter uploads to a specific folder for a custom-post type called "document" only for PDFs.

So far, I have:

function custom_upload_directory( $args ) {
$base_directory = '/home/xxx/my_uploadfolder';
$base_url = 'http://xxxx/wp-content/uploads/my_uploadfolder';

$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
// Check the post-type of the current post

if( "document" == get_post_type( $id ) || "document" == get_post_type( $parent ) ) {
    $args['path'] = $base_directory;
    $args['url']  = $base_url;
    $args['basedir'] = $base_directory;
    $args['baseurl'] = $base_url;


return $args;
add_filter( 'upload_dir', 'custom_upload_directory' );

It works, but with some problems: : any kind of file is redirected in my_uploadfolder. Also, I can't delete these files from WP admin once there. Can somebody help?

3 Answers 3


you might consider using

if(get_post_mime_type($id) == 'application/pdf'){

to check for pdf files.


You might also take a look at the code behind the wp_delete_attachment() function and you can hook into it with the delete attachment action. To remove the files you can use unlink()



The reason you're having trouble here is that you're applying a universal filter to upload_dir. Rather than doing this, use a conditional filter for upload_dir after first checking ['mime-type'] for application/pdf. You need to intercept the upload process at the wp_handle_upload action hook and alter the upload folder there. What you have posted is heading in the right direction, but you need to be working with the incoming $_POST data and applying the filter there by searching for uploading files ['mime-type'] which WordPress stores during the upload process.


I know this was 10 years ago but just incase someone is looking for code that works this will make a pdf folder in your uploads and put all pdf there so yourl will be siteurl/wp-content/uploads/pdf/filename.pdf

function custom_upload_directory( $args ) {
    // Check if the uploaded file is a PDF
    if ( ! empty( $_FILES['async-upload']['type'] ) && $_FILES['async-upload']['type'] === 'application/pdf' ) {
        // Define the custom folder path
        $custom_folder = WP_CONTENT_DIR . '/uploads/pdf/';
        $custom_url = WP_CONTENT_URL . '/uploads/pdf/';
        // Add the file name to the custom folder path
        $file_name = $_FILES['async-upload']['name'];
        $custom_folder = $custom_folder . $file_name;
        $custom_url = $custom_url . $file_name;
        $args['path'] = dirname($custom_folder);
        $args['url'] = dirname($custom_url);
        $args['basedir'] = dirname($custom_folder);
        $args['baseurl'] = dirname($custom_url);

    return $args;
add_filter( 'upload_dir', 'custom_upload_directory' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.