How to upload multiple images or files from frontend in wordpress without any plugin

How to upload multiple images or files from frontend in wordpress without any plugin

In this tutorial I will let you know about upload multiple images or files in wordpress with custom code on front-end. If you want to brings same functionality in your wordpress website is easy and use the following code which helps you to upload multiple files or images.

Add this function in functions.php

<?php

function my_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 ( is_numeric( $attach_id ) ) {
      $current_user = wp_get_current_user();
      add_user_meta( $current_user->ID, 'gallryimages', $attach_id )
  }
  return $attach_id;
}
?>

Add below code with html form in your template

//IF any file is attached
if ( $_FILES ) {
    $files = $_FILES["files"];  
    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 ("files" => $file); 
                    foreach ($_FILES as $file => $array) {              
                        $newupload = my_handle_attachment($file,$pid); 
                    }
            } 
        } 
    }
?>
//HTML

<form class="formimages" action="" enctype="multipart/form-data" method="post">
<label>Select Images</label>
<input type="file" name="files[]" id="gallery-photo-add" multiple> <small>Max 2 MB (PNG, JPEG, JPEG)</small>
<input type="submit" value="Upload" class="saveyt" name="submitdata">
</form>

Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Add your comment