Search code examples
phpwordpresswoocommerceproductgallery

WooCommerce add product image to gallery automatically (if gallery is empty)


In WooCommerce, a product can have product image (single image) & product gallery (multiple images).

When I select a product image for a product, I want it to automatically add up to the product gallery as well.

One important thing: it should check if the product image is already in the gallery or not (so the gallery won't have a duplicate image).

Is there a php function for that?

(I suspect these lines of code might help to create the function)


Solution

  • I solved it by adding the product image to the gallery array in the template itself.

    <?php
        global $product;
        $attachment_ids = $product->get_gallery_image_ids();
        $product_image_id = $product->get_image_id();
    
        // Add product image to gallery if its not there.
        // (This will prevent empty galleries, and also prevent duplicate images)
        if (!in_array($product_image_id, $attachment_ids)) {
            array_unshift($attachment_ids, $product_image_id);
        }
    
        foreach ($attachment_ids as $attachment_id) :
            $attachment_full_url = wp_get_attachment_image_src($attachment_id, 'full')[0];
        ?>
            <div class="swiper-slide"><a href="<?php echo $attachment_full_url; ?>"><?php echo wp_get_attachment_image($attachment_id, 'woocommerce_single'); ?></a></div>
        <?php
        endforeach;
    ?>
    

    However, a better solution would be to actually add the product image to the gallery itself, instead of a having a template code do that.