我正在尝试将各种图片从网址上传到给定的woocommerce
产品。我对我的代码所面临的问题是,虽然我看到图像正在上传到服务器,但当我去看我的帖子时,我只看到上传到图库的最后一张图片。
这是我的代码:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
$res3 = update_post_meta($post_id, '_product_image_gallery', $attach_id);
}
这就是我如何调用函数
for ($j=1; $j <$picCount ; $j++) {
generateSecondImage($pic[$j]->url, $post_id);
}
我想也许,res3
正在覆盖图库并仅显示最后发布的图像,但如果是这种情况,我如何告诉wordpress
将所有图像包含在for loop?
答案 0 :(得分:1)
终于设法解决了!
这是我的最终代码。我的上传功能如下:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
echo "Attach ID is".$attach_id;
return $attach_id;
}
然后我必须创建以逗号分隔的ID列表并将其添加到add_post_meta
所以我的循环改为:
for ($j=1; $j <$picCount ; $j++) {
$attarray[] = generateSecondImage($pic[$j]->url, $post_id);
}
$commaList = implode(', ', $attarray);
$res3 = add_post_meta($post_id, '_product_image_gallery', $commaList);
希望这可以帮助其他人寻找解决方案。