naeemqaswar
11/14/2016 - 10:15 AM

Multiple File Upload for POST

Multiple File Upload for POST

<!-- Refence: http://www.kvcodes.com/2013/12/create-front-end-multiple-file-upload-wordpress/ -->


<!-- HTML -->
<form action="kv-upload.php" method="post" enctype="multipart/form-data" name="front_end_upload" >
	<label> Attach all your files here :<input type="file" name="kv_multiple_attachments[]"  multiple="multiple" > </label>
	<input type="submit" name="Upload" >
</form>

<?php
    //PHP Code

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

    //PHP Code for functions.php
	function kv_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 you want to set a featured image frmo your uploads. 
        if ($set_thu) set_post_thumbnail($post_id, $attach_id);
        return $attach_id;
    }
?>