如何在WooCommerce中为产品分配多个图像?
我试过了:
update_post_meta( $post_id, '_product_image_gallery', $image_id);
但它只分配一个图像。当我使用数组时,它不起作用:
update_post_meta( $post_id, '_product_image_gallery', array($image_id,$image_id2));
答案 0 :(得分:1)
如果您需要将多个图像分配给产品,则需要将一个图像指定为特色图像/缩略图,然后将其余图像指定为产品库缩略图。
以下是一个可以为您实现此目的的快速功能:
function so_upload_all_images_to_product($product_id, $image_id_array) {
//take the first image in the array and set that as the featured image
set_post_thumbnail($product_id, $image_id_array[0]);
//if there is more than 1 image - add the rest to product gallery
if(sizeof($image_id_array) > 1) {
array_shift($image_id_array); //removes first item of the array (because it's been set as the featured image already)
update_post_meta($product_id, '_product_image_gallery', implode(',',$image_id_array)); //set the images id's left over after the array shift as the gallery images
}
}
假设您有一个图像ID数组,以及要将图像附加到的产品的ID,您可以像这样调用上面的函数:
$images = array(542, 547, 600, 605); //array of image id's
so_upload_all_images_to_product($product_id, $images);
如果您正在处理大量产品图片,或者您对微优化非常认真,则可以使用array_reverse和array_pop代替array_shift的组合。
答案 1 :(得分:0)
试试这样:
update_post_meta( $post_id, '_product_image_gallery', $image_id.",". $image_id2);
完成示例:
$images_ids = array();
$images_meta = "";
foreach ($images_ids as $im_id) {
if (is_null(get_post_meta($post_id,"_product_image_gallery")))
add_post_meta($post_id,"_product_image_gallery",$im_id);
else {
$images_meta = get_post_meta($post_id,"_product_image_gallery",true);
update_post_meta($post_id,"_product_image_gallery",$images_meta.",".$im_id);
}
答案 2 :(得分:0)
这里是这份工作的小包装。它仅接受一个附件,并将其添加为基本图像,或者如果产品已经具有基本图像,则将其添加到图库。
/**
* @param $product WC_Product|WP_Post
* @param $attachmentId int
*/
function setOrAddImageToProduct($product, $attachmentId)
{
if(!has_post_thumbnail($product->ID)) {
set_post_thumbnail( $product, $attachmentId );
} else {
$gallery = get_post_meta($product->ID, '_product_image_gallery');
if(!empty($gallery)) {
$galleryItems = explode(",", $gallery);
$galleryItems[] = $attachmentId;
} else {
$galleryItems = [$attachmentId];
}
update_post_meta($product->ID, '_product_image_gallery', join(',', $galleryItems));
}
//Adds connection to the product for the media view
$attachment = get_post( $attachmentId );
$attachment->post_parent = $product->ID;
wp_update_post( $attachment );
}