Search code examples
phpimagewoocommerceproduct

Grouped product images in woocommerce


HEEEELP!

I have a woocommerce site with grouped products, each child product has its own images, so they can be reached separatly.

I want to include all child product images in grouped product gallery. So, in case of child image is changed, the grouped product gallery is changed also.

I have tried this code:

    function get_data_from_chid_products() {

    global $product;

    if (!$product instanceof WC_Product_Grouped){
        return;
    }


    $child = $product->get_children();

    $images = [];

    foreach ($child as $key => $value) {

        $child_product_data = wc_get_product($value)->get_data();

        if ($key == 0){

            $main_image = $child_product_data['image_id'];

        } else {

            $images[] = $child_product_data['image_id'];
        }

        foreach ($child_product_data['gallery_image_ids'] as $value) {

            $images[] = $value;
        }
    }

    $unique_image_ids = array_unique($images); 

   $product->set_image_id($main_image);
   $product->set_gallery_image_ids($unique_image_ids);
   $product->apply_changes();
}
add_action( 'init', 'get_data_from_chid_products', 5 );

Is any anybody have any suggestions


Solution

  • I have find the solution!!!

    add_action( 'woocommerce_product_thumbnails', 'get_data_from_chid_products', 1);

    I figured it out while reading this https://wordpress.stackexchange.com/questions/300194/the-correct-way-to-override-woocommerce-product-gallery-from-a-plugin?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa