0

I have a form in the frontend that lets the user upload multiple images and other file types as needed. To process multiple files array I have followed this answer and here is the relevant.

PHP

global $post;
if ($_FILES) {
    $files = $_FILES['upload'];
    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
            'name'     => $files['name'][$key],
            'type'     => $files['type'][$key],
            'tmp_name' => $files['tmp_name'][$key],
            'error'    => $files['error'][$key],
            'size'     => $files['size'][$key]
            );

            $_FILES = array("upload" => $file);
            foreach ($_FILES as $file => $array) {
                $newupload = wp_insert_attachment($file,$post->ID);
            }                                   
        }
    }
}

HTML Please note that my form allows multiple images array eg. upload[]

<form method="post" id="attachment--form" action="" enctype="multipart/form-data" >
<input type="file" multiple="true" name="upload[]">
<?php wp_nonce_field('upload_attachments_nonce','secure_upload'); ?>
<input type="submit" id="upload_attachments_button" name="upload_attachments" value="UPLOAD">
<form>

I would like to check filetype using native wordpress functions wp_check_filetypes, The codex doesnot say much about it. Please help me with an example.

1

Finally figured it out. This code throws an error if the filetype is not allowed. Hope this helps some newbie save a little time.

global $post;//http://wordpress.stackexchange.com/questions/39753/
if ($_FILES) {
      $files = $_FILES['upload'];
      foreach ($files['name'] as $key => $value) {
      if ($files['name'][$key]) {
      $file = array(
      'name'     => $files['name'][$key],
      'type'     => $files['type'][$key],
      'tmp_name' => $files['tmp_name'][$key],
      'error'    => $files['error'][$key],
      'size'     => $files['size'][$key]
      );


      $uploaded_file_type = $files['type'][$key];
      $allowed_file_types = array('image/jpg', 'image/jpeg', 'application/pdf');
      if(in_array($uploaded_file_type, $allowed_file_types)) {
                //if in array run the attachment function
                        $_FILES = array("upload" => $file);
                        foreach ($_FILES as $file => $array) {
                        $newupload = insert_attachment($file,$post_id);
                        }

        } else { // wrong file type
            $upload_error .= "Invalid File Type. <br />";
            }   
        }
     }
     }

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.