How can I assign multiple images to a product in WooCommerce?
I've tried:
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:
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:
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.
Here is a little wrapper for this job. It accepts only one attachment and adds it either as the base image or adds to the gallery if the product has a base image already.
Try like this:
Example to complete: