2013-02-12 69 views
0

我試圖上傳多個文件並將它們附加到Wordpress文章。 該代碼與單個圖像的偉大工程:使用HTML 5和PHP多文件上傳

PHP

function insert_attachment($file_handler,$post_id,$setthumb='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 ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); 
     return $attach_id; 
} 

if ($_FILES) { 
    foreach ($_FILES as $file => $array) { 
    $newupload = insert_attachment($file,$pid); 
} 

HTML

<fieldset class="images"> 
    <label for="images">Images</label> 
    <input type="file" name="images" id="images" tabindex="25"/> 
</fieldset> 

但我怎麼能使其與多個圖像工作?

我知道我必須添加multiple="multiple"到輸入,輸入的名稱應該是images[]。但我肯定有PHP腳本的問題。

+2

[上傳多個文件(http://php.net/manual/en/features.file-upload.multiple .php) – 2013-02-12 07:11:42

+0

感謝您的參考,@Akam。不過,如果您能演示如何將其應用於我的PHP部分,我將非常感激。 – Sergey 2013-02-12 07:15:37

+0

它更好地使用多個而不是使用HTML5多個功能,因爲它目前不能交叉兼容。 – 2013-02-12 07:34:58

回答

1

萬一有人需要這個未來:我找到了解決辦法here

// If we have files 
if ($_FILES) 
{ 
    // Get the upload attachment files 
    $files = $_FILES['upload_attachment']; 

    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("upload_attachment" => $file); 

      foreach ($_FILES as $file => $array) 
      { 
       $newupload = insert_attachment($file,$post->ID); 
      } 
     } 
    } 
}