Help to upload post attachments from Ajax


My problem is that I cannot upload post attachments from a frontend form. I send data through AJAX to my php files containing functions. Let me be clear: everything is working great, the post is created with all informations. The only missing thing is that the images I sent are not attached to the post.

My problem should be in my php function to attach images.

My html

<input id="moreimages" type="file" name="moreimages[]" multiple >

My php function

$pid = // project id
$uid = // current user

if ( $_FILES ) { 
$files = $_FILES["moreimages"];  
foreach ($files['name'] as $key => $value) {            
            if ($files['name'][$key]) {
                $upload_overrides             = array('test_form' => false);
                $uploaded_file                = wp_handle_upload($_FILES['file'], $upload_overrides);
                $file_name_and_location       = $uploaded_file['file'];
                $file_title_for_media_library = $_FILES['file']['name'];
                $arr_file_type      = wp_check_filetype(basename($_FILES['file']['name']));
                $uploaded_file_type = $arr_file_type['type'];
                $image = array( 
                    'post_mime_type' => $uploaded_file_type,
                    'post_title' => addslashes($file_title_for_media_library),
                    'post_content' => '',
                    'post_status' => 'inherit',
                    'post_parent' => $pid,
                    'post_author' => $uid
                $_FILES = array ("moreimages" => $image); 
                foreach ($_FILES as $images => $array) {              
                    $image_id = wp_insert_attachment($image, $file_name_and_location, $pid);
                    $attach_data = wp_generate_attachment_metadata($image_id, $file_name_and_location);
                    wp_update_attachment_metadata($image_id, $attach_data); 

I repeat I see in my console.log that images are correctly sent by AJAX into FormData object. I see this when I upload FIRST.jpg.

Content-Disposition: form-data; name="moreimages[]"; filename="FIRST.jpg"
Content-Type: image/jpeg

So the problem should be in the php loop for attaching images. Could you help me please? Thanks in advance!

, , , , Kleeia 8 months 0 Answers 96 views 0

Leave an answer