Create Front-end Multiple File Upload – WordPress |
X

Congrats, You are Subscribed to Receive Updates.

Create Front-end Multiple File Upload – WordPress


WordPress  can provide you multiple file upload support and drag and drop support on admin section. If  you wish to bring the same service on your WordPress front end is easy and the following code help you to create multiple file upload with the help of HTML5 Forms and simple WP function.

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

create-front-end-multiple-file-upload-wordpress
The above form sent the form data to the HTML file kv-upload.php  . Here is the simple upload php function to handle multiple files simultaneously.

//kv-upload.php 
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); 
					}
				} 
			} 
		}

}

Here we gather the files which sent by the HTML forms. and send it to another function called kv_handle_attachement(). This is a simple function this will help you to store the files to your wp uploads directory. Add the following code into your Theme “ 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;
}

This will help you to handle multiple file upload from your front end of WordPress site.  If you have any doubt in it,  Just leave a comment here.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

58 comments

  1. commenter

    This is great. I have one question though. Is there a way for the files to be attached to a post (at the moment they end up being ‘unattached’)?

    For example, on the front-end I have the upload field appearing at the end of all posts. When I hit submit and my files get uploaded they would ideally be attached to the post they came from. So when I view them in the Media area of WordPress admin I can see which posts the files are attached to.

    Thanks in advance.

    • commenter

      Hi Dave,
      You can do this by simply passing post id with the kv_handle_attachment() function. From my example code is already have the parameter. Check here. kv_upload.php file on nearly line no: 16 is like “$newupload = kv_handle_attachment($file,$pid); ” . Here $pid is stands for post id. Just pass it to make your attachments as “attached“. Without Post ID, the uploaded file will be unattached. If any queries revert me a reply.

      • commenter

        Hi Thanks for this, Im very close!

        I too am trying to make all uploads attach to the post they have come from.

        can you please re-write the above to make sure it is attached to the post? Thanks, I will donate to your via paypal?

        • commenter

          Post contents are retrieved from database, would you like to upload your medias into the database, or just want to create a separate folder for a post to handle its medias, ? explain me a little more, how you looking.

  2. commenter

    Hello,

    Your article is very helpful to everyone. Who want to upload the image from frontend of wordpress. To be frank, am trying your code but i get many errors, but i fix according to the requirement but still am not able to upload image.

    let me tell how i can implement your code:

    simple i create a plugin.
    Create a file name image.php
    In Image.php , i’ve create a form and give action to kv-upload.php
    In kv- upload.php file , i mention the whole function and code which is describe by you post.

    but i am still get error is like ,

    Fatal error: Call to undefined function __() in D:\xampp\htdocs\nd\wp-admin\includes\file.php on line 13

    Fatal error: Call to undefined function add_filter() in D:\xampp\htdocs\nd\wp-admin\includes\media.php on line 57

    Fatal error: Call to undefined function media_handle_upload() in D:\xampp\htdocs\nd\wp-content\plugins\wp-image\kv-upload.php on line 14

    Function are undefined. plugins can’t support the single function of wordpress.
    For supporting of all function i also required_once function to get wp-load.php file.

    So its upto you how you can give me wright way to upload image from frontend.

    Please define whole step (where function put in which file) how do i implement your code.

    Thanks in Advance
    Please Reply ASAP

    • commenter

      Yes, you are necessary to add the following code on your theme ” 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;
      }
      
  3. commenter

    plz tell me how to get the all images.

  4. commenter

    Hi,i want to use this as attach images in comment.

    I put this in comments-review.php

    Attach all your files here :

    And this into 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;
    }
    

    And this into comments-listing.php

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

    —–

    But how to show the images ???

    • commenter

      These attachments are stored as post. So query it when a comment is posted with attachment.

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

      Inside the function add a custom meta for attachments to a comment.

      Try this, if you can’t do anything. Contact me again through my contact page.

    • commenter

      Can you tell me where is the fault of mine?

      // Add field
      function action_woocommerce_edit_account_form_start() {
      ?>

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

      }

      // 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’);

      $attachment_id = media_handle_upload( $file_handler, $post_id );

      if ( $attachment_id ) {

      update_user_meta( $user_id, $attachment_id );
      }

      add_action( ‘woocommerce_save_account_details’, ‘action_woocommerce_save_account_details’, 10, 1 );

      // Add enctype to form to allow image upload
      function action_woocommerce_edit_account_form_tag() {
      echo ‘enctype=”multipart/form-data”‘;
      }
      add_action( ‘woocommerce_edit_account_form_tag’, ‘action_woocommerce_edit_account_form_tag’ );

      // Display
      function action_woocommerce_edit_account_form() {
      // Get current user id
      $user_id = get_current_user_id();

      // Get attachment id
      $attachment_id = get_user_meta( $user_id, $newupload, true);
      // True
      if ( $attachment_id ) {

      // Display Image instead of URL
      echo wp_get_attachment_image($attachment_id, $newupload);
      }
      }
      add_action( ‘woocommerce_edit_account_form’, ‘action_woocommerce_edit_account_form’, 10, 2 );

  5. commenter

    Hi, I just came by and saw this site. nice work

  6. commenter

    Hi,

    Thank you for your code, I was trying to implement it and it works but have a few questions, it would be nice if you can help.

    I have created frontend form that submits post title, post content etc, it works nicely.

    Now I want to upload and attach images to the post that i am submitting.

    I know that images url comes from DB so first i would need to upload the images, which your code helped with.

    Now I want the url or attachment id to be returned to the browser so that i can add that to the post that i am submitting, that way these images can get attached.

  7. commenter

    Hi , ive been looking for this and it seems like a great solution .
    I implemented it exactly by your instructions.
    for some reason though , probably related to permalinks and so on… i cant seem to submit..
    im getting an 404 error that the kv-upload file cant be found on my server.

    I uploaded the kv-design to the root of my theme as kv-upload.php

    any idea how to make wordpress “see” this file?

    im also wondering if i can make it write the pathes to the uploaded files in a custom field…
    but i need to get it working first.

    thanks in advance 🙂

    • commenter

      you can do it. just play with the code well. its will help you to save custom files and retrieve it. if you want to change the uploads path, just use the following one on config,

       
      define('UPLOADS', '/your/custom_path/for/uploads');
      
  8. commenter

    Hi
    Where do I put the file kv-upload.php in my site? What directory so the function.php file will see it?

    Thanks in advance
    Dean-O

    • commenter

      Inside your WordPress theme. I mean current active theme.

      Are you started learning WordPress.?

      • commenter

        I have been working with wordpress for a couple of years. If I put the kv-upload.php file in my theme I get sitename/kv-upload.php file not found. If I put kv-upload in my root directory of my site, it finds the file but then I get an error in my php log saying undefined function kv_handle_attachment The action for my form on my page is form action=”kv-upload.php” method=”post” how do I tell it to go to the kv-upload.php that is in my theme?

  9. commenter

    I have been working with wordpress for a couple of years. If I put the kv-upload.php file in my theme I get sitename/kv-upload.php file not found. If I put kv-upload in my root directory of my site, it finds the file but then I get an error in my php log saying undefined function kv_handle_attachment The action for my form on my page is form action=”kv-upload.php” method=”post” how do I tell it to go to the kv-upload.php that is in my theme?

  10. commenter

    If there are two input files in the form, How to handle it? I used your code, but only upload the first attachments

    Attach all your files here :
    Attach all your files here :

  11. commenter

    Hello,

    Thanks for the great tutorial. It ist very usefull. Can you tell me please, how can i edit an existing field (image field).

    I have created a front-end form, with which I can edit the content of posts. I can without Problem update the content. But only the image field would not updated.

    After Submitting the From:
    $post_information = array(
    ‘ID’ => $current_post,
    ‘post_title’ => esc_attr(strip_tags($_POST[‘postTitle’])),
    ‘post_content’ => $_POST[‘postContent’],
    ‘post-type’ => ‘page’,
    ‘post_status’ => ‘publish’
    );
    $post_update = wp_update_post($post_information);

    update_post_meta($current_post,’_url’, $_POST[‘headerimage’]);
    image_attachment($_POST[‘headerimage’], $current_post);

    the Function: image_attachment

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

    When i check the Variable $headerimage[url], i find that the Variable is empty.

    It works well. But the record of the image will not be updated.

    Maybe one of you can help me. For any help I would be grateful.

    Thanks in advance
    Emidio

    • commenter

      are you editing a post image or image url. ?

      if its url, just go with $_POST[]

      if you are editing image, than use $_FILES{] to replace the new file and once its uploaded you can update the post meta.

  12. commenter

    Hello Varadharaj V,

    Many thanks for your response!
    I have a form where the user can edit his page. On the page there is a header graphic. The user can upload with a upload form an image or replace an existing image. I have tested the form with $_FILES and with $_POST
    “update_post_meta($current_post,’headergrafik’, $_POST[‘headergrafik’]);”.

    The images are uploaded. But when I run the page header graphic is not displayed because the variable is empty.

  13. commenter

    i am new to front accounting how to add new links to the existing front accounting

  14. commenter

    Can we upload any types of file? I want to upload doc. pdf typles file , will it be helpful to me? Please can you reply as soon as possingle on my email?

  15. commenter

    Wow! You are genius.
    This is the best explanation on front-end upload I have ever found. Thank you! Thank you!! Thank you!!! But how can I use this form in my WordPress BBPress forum to attach images to topic/post? I want forum members/participants to upload and attach images to their posts. Please help. I will donate to this great site.
    Thank you once again.

  16. commenter

    Thank you for quick response. My skill of CSS is excellent now. But my skill of PHP and Jquery is still underdeveloped. Could you please cook for me any posible code I can test? Thanks.

  17. commenter

    Hi,

    I’m trying to use your method to upload multiple images with different names (i.e. different input fields) there will be two uploads, actually. One will be the post thumbnail and the other will be attached as a custom post_meta as ‘post-cover-photo’ after days of work I couldn’t manage to achieve this. functions.php part is working fine, but I have problems with different names.

    Can you help? Thanks very much.

    The stackoverflow question is here : http://stackoverflow.com/questions/31763123/php-upload-multiple-files-with-different-input-field-names-using-media-handle-up

  18. commenter

    It works fine with me.
    But needed to use the same code with a progress bar jquery, html5 js or without flash, but seems to be very difficult to implement this, have any idea how to do this?

  19. commenter

    how if i only want to upload 1 image?

  20. commenter

    Hi,

    Thanks for this tutorial.

    It seems that the kv-upload.php file not taking as well. net::ERR_CONNECTION_RESET issue is there.

    I just follow the instructions of the tutorial, and also tried with template directory path to the action like : action=”/kv-upload.php”

    And it shows the kv_handle_attachment – not found error.

    Please help.

    • commenter

      I think its a problem with file hooking. better remove the form action and place the html form and “kv-uploads.php” code on a same file and try it. I hope it will work this time.

  21. commenter

    Hello

    This kind of process, I use for video uploading on frontend submission. It can be working.

  22. commenter

    I must say I am a little bit overwhelmed with all this.
    In fact I’ve been trying to find a way on how to let my visitors upload a file either in a post or in a comment, but in the same time to create the upload path in a way it would relate to the particular post (for example to create a subfolder with a post name or post id in the uploads directory). Then I would also like to list in each post all the files uploaded this way (in fact only the files referring to the particular post wold be listed in that post). (I used a plugin called “MMM Simple File List” for this).
    I could not find the plugin which would help me do this (I tried with “WordPress File Upload”, but it seem to be limited to page titles and can not create subfolders based on post names or post ids).
    Based on what I can understend, the process you are describing here would be able to help me do what I want, but I seem to be to stupid to understand how to implement it.
    Where do I put all these codes? I read someone here saying I need to create my own plugin.php?! Can you give some basic instructions to the noob as myself?
    Anyway, congratulations on your good work and hope to read from you.
    Thanks!

    • commenter

      Of-course, you can make it as plugin and integrate in anysite. But thing is,you need to get a page or widget or short-code to make this codes run on front page. than you can rock it by making it as plugin. At present i am engaged with different jobs. So,i am not available for free plugins. if you need, you can make it from scratch and by using these above functions

      Thanks for your feedback.

  23. commenter

    This code snippet is great. It seems to work really well for multiple files of one type.
    In my code, I’ve turned your snippet into a reusable method that I can call several times for different files on the $_FILES array. However, where I set $_FILES = array ($file_type => $file); it overrides the global $_FILES variable and when I call the method again, $_FILES is no longer set to the form data but rather the new array.

    My question is: Is there a particular reason you have to overwrite $_FILES?

    I’ve tried setting $files_array = array ($file_type => $file); and looping over that variable but it never seems to work even though it contains the same data that $_FILES has after it’s overwritten. Is there a way to solve this problem?

  24. commenter

    Dear, i try to create a new post from front end and $_FILES seems to be empty, and i do not find why,
    var dump return : array(0) { }

    this is my code, if someone see what i can’t see

    $postTitleError = '';
    if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
     
        if ( trim( $_POST['postTitle'] ) === '' ) {
            $postTitleError = 'Please enter a title.';
            $hasError = true;
        }
     
        $post_information = array(
            'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
            'post_content' => $_POST['postContent'],
            'post_type' => 'homestay',
            'post_status' => 'pending'
        );
    	
    	$post_id = wp_insert_post( $post_information );
     	if ( $post_id ) {
    		echo $post_id;
    		
    		var_dump( $_FILES );
    		
    	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,$post_id); 
    					}
    				} 
    			} 
    		}
        	//wp_redirect( home_url() );
        	exit;
    	}
    }
    
  25. commenter
    Barry Michael Doyle

    Where do the files get uploaded to using this approach?

  26. commenter

    Thanks for great work, but how can I display all uploaded files and allow user to download on front page,
    Please help me .
    Thanks in advance

  27. commenter

    hello, i get the error ” invalid argument supplied for foreach () ”
    i also added if(is_array($kv_multiple_attachments) || is_object($kv_multiple_attachments)){} but didn’t work again.

  28. commenter
    Upendra Nishad

    Hii,

    I am having a doubt
    Can this plugin do like

    Page 1 contains abc.xml, def.xml, xyz.xml

    &

    Page 2 contains 123.jpg, 1234.jpg, 1827.png

    So i want that this all uploaded files should not visible in all pages.
    Sperate page will have separate files.

    • commenter

      i am not sure you understand the point. we can upload files with this code. cant split them for pages. may be write one more hook to distinguish the files with extension to show it on pages.

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar