簡體   English   中英

如何使用wp_insert_post上傳多張圖片

[英]How to upload multiple image using wp_insert_post

我正在使用wp_insert_post在woocommerces網站的前端添加產品

我當前的代碼將上傳所有圖像,但是只有最后一個圖像將出現在產品庫圖像中

這是我的代碼;

functions.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 ) ) {

    update_post_meta( $post_id, '_product_image_gallery', $attach_id );

  }
  return $attach_id;  
}

前端

if ( $_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 = my_handle_attachment($file,$post_id);
            }
        }
    }
}


<input type="file" name="upload_attachment[]" multiple="multiple"  />

我在這里做錯了什么?

您能否嘗試在代碼中進行更改,然后再試一次,我在進行wordpress項目時記得這一點。

    $attachment_id = media_handle_upload($file, $post_id);
    update_post_meta($post_id,  array_push($post_id, '_product_image_gallery', 
    $attachment_id));
    return $attachment_id;

請嘗試這個

function my_handle_attachment($file_handler, $post_id)
{
  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 )) 
 {
 update_post_meta( $post_id, '_product_image_gallery', $attach_id );
 array_push($post_id, '_product_image_gallery', $attach_id)
 }
 return $attach_id;  
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM