Creating a multi-file upload form on the front end for attachments

I am trying to create a public form where users can upload multiple images to be attached to a particular post. I am able to get it to work with single images thanks to this post at Golden Apples Design.

The problem is that I’m struggling with multiple file uploads. I’ve changed

<form method="post" action="#" enctype="multipart/form-data" >
  <input type="file" name="upload_attachment">
  <input type="submit">
<form>

to
<form method="post" action="#" enctype="multipart/form-data" >
  <input type="file" multiple=multiple name="upload_attachment[]">
  <input type="submit">
<form>

Now the $_FILES array is in a different format and the file handler doesn’t handle it properly. Can anyone help me figure out how to loop through the array in the correct way and feed the file hander the format it wants?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This may not be the most elegant way to do it (I’m not sure if overwriting the $_FILES global is even allowed) but this seems to work:

global $post;
if ($_FILES) {
    $files = $_FILES['upload_attachment'];
    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_attachment" => $file);

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments