WordPress – Upload multiple images to gallery from front end

I have a form on frontend in wordpress page template. I want the users to submit their images and those images should be inserted into wordpress media gallery automtically. I have tried everything and attachments are being inserted but there are no corresponding images in the uploads folder and hence images give 404 error.

Here is my form

Read More
<input type="file" name="gallery[]" id="gallery" multiple="true" accepts="image/*" data-rule-required="true" data-msg-required="Please attach at least one photograph">

Here is the php code to upload and get image attachments:

    if(isset($_FILES['gallery']))
{    
  for($i=0; $i<count($_FILES['gallery']['name']); $i++) {
  //Get the temp file path
  $filename = $_FILES['gallery']['name'][$i];
    echo $filename;
  //Make sure we have a filepath
  if ($filename != ""){
      $filetype = wp_check_filetype( basename( $filename ), null );
      $wp_upload_dir = wp_upload_dir();
      //echo $filetype['type'];
      $attachment = array(
    'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
    'post_mime_type' => $filetype['type'],
    'post_title'     => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
    'post_content'   => '',
    'post_status'    => 'inherit'
    );
    $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );  
    array_push($images,$attachment_id);
  }
}
}

What I am doing wrong . Any help will be highly appreciated

Ahmar

Related posts

1 comment

  1. Have you checked if your /wp-content/uploads directory has the neccessary permissions to upload a file?
    Try to set the permissions to 755

Comments are closed.