我使用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" />
我在这里做错了什么?
答案 0 :(得分:0)
您可以尝试在代码中更改此内容并尝试一次,我会在处理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;
答案 1 :(得分:0)
请试试这个
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;
}