Friday, May 29, 2015

Wordpress - multiple file upload from front end

Wordpress provide us multiple file upload from admin section. Now in this section we will learn, how we do the same thing from front end. 

Below is the form for multiple file uploads:

<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="multiple_attachments[]"  multiple="multiple" >

<input type="submit" name="Upload" >
</form>

Below is the simple upload php function to handle multiple files simultaneously.

if( isset($_POST['Upload'])) {
$files = $_FILES["multiple_attachments"]; 

 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 ("multiple_attachments" => $file);


foreach ($_FILES as $file => $array) {$newupload = handle_attachment($file);}}}
}


In the above script, we gather the files from HTML forms and send it to another function called handle_attachment(). This function help us to store the files in our wp uploads directory.

function handle_attachment($file_handler) {
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);        

}


Put above function in function.php file of current theme.