向 WooCommerce 产品添加多个图像 [英] Add multiple images to WooCommerce product

查看:53
本文介绍了向 WooCommerce 产品添加多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 WooCommerce 中为一个产品分配多个图像?

How can I assign multiple images to a product in WooCommerce?

我试过了:

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

但它只分配一个图像.当我使用数组时,它不起作用:

but it assigns only one image. When I use an array, it does not work:

update_post_meta( $post_id, '_product_image_gallery', array($image_id,$image_id2));

推荐答案

如果您有多个图片需要分配给一个产品,您需要分配一个图片作为特色图片/缩略图,然后分配其余的图片图像作为产品库缩略图.

If you have multiple images that need to be assigned to a product, you will need to assign one image as the featured image/thumbnail, and then assign the rest of the images as the product gallery thumbnails.

以下是可以为您实现此目的的快速功能:

Below is a quick function that can achieve this for you:

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,您可以像这样调用上面的函数:

Assuming you have an array of image id's, and the id of the product that you want to attach the images to, you can call the function above like this:

$images = array(542, 547, 600, 605); //array of image id's
so_upload_all_images_to_product($product_id, $images);

如果您正在处理大量产品图片,或者您对微优化非常认真,您可以使用 array_reversearray_pop 而不是 array_shift.

If you are working with a massive array of product images, or you are very serious about micro-optimisation, you can use a combination of array_reverse and array_pop instead of array_shift.

这篇关于向 WooCommerce 产品添加多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆