Upload Multiple Files With media_handle_upload

I have a WordPress form plugin and I use media_handle_upload to upload the files and get there ids directly and attached its ids to the post as a meta date, I used the following to did that:

The HTML of the form field is:

<input type="file" name="my_file_upload" id="my_file_upload">

And the php code was:

$attach_id = media_handle_upload( 'my_file_upload', $post_id );
if ( is_numeric( $attach_id ) ) {
    update_post_meta( $post_id, '_my_file_upload', $attach_id );
}

And everything was work perfectly.

Now I am trying to upload multiple files my HTML code is:

<input type="file" name="my_file_upload[]" id="my_file_upload[]" multiple="multiple">

But I cant make the media_handle_upload function work with multiple files upload.

Any help will be appreciated.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

here
if you use custom template past this in the begining

<?php
 if( 'POST' == $_SERVER['REQUEST_METHOD']  ) {
if ( $_FILES ) { 
    $files = $_FILES["my_file_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 ("my_file_upload" => $file); 
                foreach ($_FILES as $file => $array) {              
                    $newupload = my_handle_attachment($file,$pid); 
                }
            } 
        } 
    }

}
?>

in function.php

function my_handle_attachment($file_handler,$post_id,$set_thu=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 ( is_numeric( $attach_id ) ) {
    update_post_meta( $post_id, '_my_file_upload', $attach_id );
  }
  return $attach_id;
}

soure http://www.kvcodes.com/2013/12/create-front-end-multiple-file-upload-wordpress/

Solution 2

If you want to implement this without using the functions file, you can use the streamlined version I came up with. This is the tested code works 100%

<form id="file_upload" method="post" action="#" enctype="multipart/form-data">
     <input type="file" name="my_file_upload[]" multiple="multiple">
     <input name="my_file_upload" type="submit" value="Upload" />
</form>

Place the PHP code on the page where the submit happens. In my case on the same page as the form action is set to “#”

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    $files = $_FILES["my_file_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" => $file);
            $attachment_id = media_handle_upload("upload_file", 0);

            if (is_wp_error($attachment_id)) {
                // There was an error uploading the image.
                echo "Error adding file";
            } else {
                // The image was uploaded successfully!
                echo "File added successfully with ID: " . $attachment_id . "<br>";
                echo wp_get_attachment_image($attachment_id, array(800, 600)) . "<br>"; //Display the uploaded image with a size you wish. In this case it is 800x600
            }
        }
    }
} ?>

This method will include the required files only once when the form submit is done instead of including them each time the function is called through foreach loop

Solution 3

Thanks @shady-m-rasmy
I used the code you mentionned, and it seems that the second foreach loop (below – in the custom template part) is not necessary as it is only executed once.

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

So it only leaves with

$newupload = my_handle_attachment( "my_file_upload", $pid);

Solution 4

Multiple entries for the same meta key

$values = [ 'red', 'yellow', 'blue', 'pink' ];
foreach( $values as $value ) {
    // This method uses `add_post_meta()` instead of `update_post_meta()`
    add_post_meta( $item_id, 'color', $value );
}

Solution 5

HTML

<input type="file" id="id_termine_attachment" multiple="multiple" name="id_termine_attachment[]" value="" size="25" />

PHP

function upload_file($_FILES) {

    if (!empty($_FILES['id_termine_attachment'])) {
        $supported_types = array(
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/msword',
            'image/gif',
            'image/jpeg',
            'image/png',
            'application/zip'
         );

        $file_arr = reArrayFiles($_FILES['id_termine_attachment']);
        $file_urls = [];

        foreach ($file_arr as $file) {
            $arr_file_type = wp_check_filetype(basename($file['name']));
            $uploaded_type = $arr_file_type['type'];
            if (in_array($uploaded_type, $supported_types)) {
                $upload = wp_upload_bits($file['name'], null, file_get_contents($file['tmp_name']));
                if (isset($upload['error']) && $upload['error'] != 0) {
                    wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
                } else {
                    array_push($file_urls, $upload['url']);

                } // end if/else
            } else {
                wp_die("This filetyp is not available!");
            }
        }
        update_post_meta($post_id, 'id_termine_attachment', $file_urls);
    }
}



function reArrayFiles(&$file_post) {
    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

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

Leave a Reply