My app allow admins to create multiple file fields in order for user to upload 1 document per field, which will be recorded in database by input field name.
An example of the different fields that could be generated:
<ul id="training_session_required_document_list" class="list-group">
<li class="list-group-item d-flex px-0">
<span class="col-6 my-auto">
document 1*
</span>
<span class="col-6 my-auto">
<input type="file" name="user_file_document-1" class="form-control user_file_field" value="">
</span>
</li>
<li class="list-group-item d-flex px-0">
<span class="col-6 my-auto">
document-2*
</span>
<span class="col-6 my-auto">
<input type="file" name="user_file_document-2" class="form-control user_file_field" value="">
</span>
</li>
</ul>
Now when I process the Form and try to upload (with WordPress) files, only first in the loop is saved.
if ( isset($_FILES) && !empty($_FILES) ) {
foreach ( $_FILES as $field => $metadata ) {
$files = $_FILES[$field];
$file = array(
//Loop through all the uploaded files
'name' => $files['name'],
'type' => $files['type'],
'tmp_name' => $files['tmp_name'],
'error' => $files['error'],
'size' => $files['size']
);
$_FILES = array( 'uploaded_file' => $file);
$file_id = media_handle_upload('uploaded_file', $post_ID);
if ( !is_wp_error( $file_id ) ) {
/*
* File uploaded successfully and you have the attacment id
* Do your stuff with the attachment id here
*/
update_post_meta( $post_ID, $field, $file_id);
} else {
}
}
}
If I var_dump($_FILES)
at the beginning I can view all my files info in 2 arrays for this example:
array (size=2)
'user_file_document-1' =>
array (size=5)
'name' => string 'Screenshot_10.jpg' (length=17)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string 'C:wamp64tmpphp16A.tmp' (length=24)
'error' => int 0
'size' => int 102337
'user_file_document-2' =>
array (size=5)
'name' => string 'Screenshot_12.jpg' (length=17)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string 'C:wamp64tmpphp16B.tmp' (length=24)
'error' => int 0
'size' => int 50005
How can I make my loop to save all the input files?