0

I'm trying to upload multiple files and attach them to Wordpress post. This code works great with single images:

PHP

function insert_attachment($file_handler,$post_id,$setthumb='false') {
    // check to make sure its a successful upload
    if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

    $attach_id = media_handle_upload( $file_handler, $post_id );

    if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
        return $attach_id;
}

if ($_FILES) {
    foreach ($_FILES as $file => $array) {
    $newupload = insert_attachment($file,$pid);
}

HTML

<fieldset class="images">
    <label for="images">Images</label>
    <input type="file" name="images" id="images" tabindex="25"/>
</fieldset>

But how can I make it work with multiple images?

I do know I have to add multiple="multiple" to the input, the name of the input should be images[]. But I definately have problems with PHP script.

6
  • 2
    Uploading multiple files Commented Feb 12, 2013 at 7:11
  • Thank you for the reference, @Akam. However I would highly appreciate if you could demonstrate how I can adopt it to my PHP part. Commented Feb 12, 2013 at 7:15
  • its better to use multiple <input type="file" name="images[]" id="images" tabindex="25"/> instead of using HTML5 multiple feature because currently its not cross compatible. Commented Feb 12, 2013 at 7:34
  • Thank you for your response, @Akam. But I would like to stick to HTML5. Commented Feb 12, 2013 at 8:24
  • 1
    @Quentin, thanks, but I don't want to have multiple inputs. Commented Feb 12, 2013 at 9:43

1 Answer 1

1

In case someone will need this in future: I found the solution here:

// If we have files
if ( $_FILES )
{
    // Get the upload attachment 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 = insert_attachment($file,$post->ID);
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.