16

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.

2
  • Use foreach to upload multiple , iam on mobile now so icant post the full code – Shady M Rasmy Dec 25 '14 at 5:01
  • I tried many foreach loops and no one of them work. – Engr.MTH Dec 25 '14 at 21:01
15

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/

4
  • Thanks for your code , i'm using it for a form to submit posts. I was wondering how i can validate uploaded files. there's a way ? – sb0k Nov 11 '15 at 18:53
  • 3
    Doesn't this overwrite the global $_FILES variable? – ReLeaf Mar 19 '16 at 20:44
  • @ReLeaf This should overwrite the global $_FILES variable. media_handle_upload() looks for $_FILES[$file_handler] – Andy Macaulay-Brook Jul 4 '18 at 20:16
  • This snippet works perfect, EXCEPT on Android WebView when trying to upload multiple files (single file is ok). – Rollor Feb 9 '19 at 17:40
9

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

1
  • EDIT: I have taken off the code $post_thumbnail_id = wp_get_attachment_image_src($attachment_id, array(800, 600)); as it is unnecessary for the example. But if you wish to get the URL of the image, it will help you :) – Lucky Sep 6 '16 at 7:30
5

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);
0

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 );
}
2
  • Can you please format your code and add also add explanation? – Nilambar Sharma Jul 2 '19 at 8:50
  • I'm not sure this solves the problem here: the hardest part seems to be parsing the submitted files, not attaching multiple files to the post. – Rup Jul 2 '19 at 9:52
0

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;
}

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.