Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Is there any way to limit the filetypes allowed for upload based on the current post type?

For example, I have a custom post type called documents. I have a File upload custom field which calls the Media Uploader (media-upload.php) and I have the possibility to upload a file. I want to restrict the file to pdf, doc and xls.

However, I also have a post type called illustrations in which I want to limit the upload file types to jpeg, png or gif.

I am currently trying Mike Schinkel's answer from Limit image upload to one and disable audio, video and other document file types to upload to restrict the file types, but I don't know how to vary the array of permitted filetypes based on the current post type.

 if ('image'!=$category || !in_array($type,array('jpg','jpeg','gif','png'))) {
    $file['error'] = "Sorry, you can only upload a .GIF, a .JPG, or a .PNG image file.";
}

I tried using get_current_screen() but it returns the id of the media uploader itself. I also tried using global $post but I didn't get anything.

Or would it be simpler to add a filter to upload_mimes based on the current post type?

Any suggestions?

Answer:

if( isset( $_REQUEST['post_id'] ) && $post_type = get_post_type( absint( $_REQUEST['post_id'] ) ) ) {

    if( 'illustrations' === $post_type ){
     $filetype = array('png', 'jpeg', 'gif', 'jpg');
     $message = 'Only PNG, JPEG, JPG, and GIF allowed.';
    }

     elseif( 'documents' === $post_type ){
      $filetype = array('doc','docx','pdf','xls', 'xlsx', 'zip');
      $message = 'Only PDF, DOC, DOCX, XLS, XLSX, and ZIP allowed. ';
    }

  }
share|improve this question

1 Answer 1

up vote 2 down vote accepted

I'm pretty sure $_REQUEST['post_id'] will hold the post ID you're attaching uploads to. So something like this perhaps:

if ( isset( $_REQUEST['post_id'] ) && $post_id = absint( $_REQUEST['post_id'] ) ) {
    switch ( get_post_type( $post_id ) ) {
        case 'document' :
            if ( ! in_array( $type, array( 'pdf', 'msword', 'vnd.ms-excel' ) ) )
                $file['error'] = '...';
            break;

        case 'illustration' :
            // and so forth
    }
}
share|improve this answer
    
Thanks a lot. Works great :) –  RRikesh Nov 6 '12 at 10:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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