Himas Rafeek
Posted on: 1 year ago

Add multiple images to WooCommerce product

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
    }
}

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);