Using media_handle_upload with array

by user1452062   Last Updated May 12, 2018 15:08 PM

I have duplicable file inputs in a form, and I would like to upload them to WordPress media library using media_handle_upload.

A form looks like this:

<form class="form mt-5" method="POST" action="" enctype="multipart/form-data">
<input type="file" name="product[0][image]">
<input type="file" name="product[1][image]">
<input type="file" name="product[2][image]">

The PHP part:

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

$i = 0;
foreach($_POST['product'] as $product) {
    $attachment_id = media_handle_upload( 'product['.$i.'][image]', $new_product );
if ( is_wp_error($attachment_id) ) {
    $errors['upload_error'] = $attachment_id;
    $attachment_id = false;

if ($errors) {
    echo "<p>There was an error uploading your file.</p>";
} else {
    echo "<p>Your file has been uploaded.</p>";

If I submit the form, I get the following error: File is empty. Please upload something more substantial.

I did a test, and kept only one file field, with name="testfile", and I also changed the parameter in media_handle_upload, and it worked.

What is the best way to submit/upload multiple files from the form?

Related Questions