帮助从AJAX上传帖子附件

时间:2016-04-29 作者:Kleeia

我的问题是,我无法从前端表单上载帖子附件。我通过AJAX 给我的php 包含函数的文件。让我明确一点:一切都很顺利,the post is created 所有信息。唯一遗漏的是,我发送的图片没有附在帖子上。

我的问题应该是php function 附加图像。

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); 
                }
            } 
        } 
    }
我重复一遍,我在控制台上看到了。记录AJAX将图像正确发送到FormData对象中。我第一次上传时看到了这一点。jpg。

Content-Disposition: form-data; name="moreimages[]"; filename="FIRST.jpg"
Content-Type: image/jpeg
因此,问题应该在附加图像的php循环中。你能帮帮我吗?提前感谢!

1 个回复
SO网友:Kleeia

我实际上忘记了创建上传和附加图像的功能。我在这里找到了另一个问题的正确方法Uploading Multiple Attachments From Front-End With A Description.