14

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?

2

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.

1

you might consider using

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

to check for pdf files.

http://codex.wordpress.org/Function_Reference/get_post_mime_type

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()

http://php.net/manual/en/function.unlink.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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