lundi 30 octobre 2023

How can I show a random image from the product gallery as the primary product image in the Woocommerce store?

I have 3 color t-shirts in my gallery. I randomly want one of these 3 tshirt images to be the primary image of my product. I want it to appear randomly on both the product page and the store pages.

I think I need a function for this, where I will leave the primary image empty and only upload 3 images to the gallery.

This code snippet shows the first image in the gallery only on the store page, but since it is not the primary image on the product page, it appears empty. But I don't want the first image, I want it randomly.

function modify_woocommerce_product_get_image( $image, $product, $size, $attr ) {
    $image_ids = $product->get_gallery_image_ids();
    if( $image_ids ) {
        $image_ids = array_merge($image_ids, array($product->get_image_id()));
        $key = array_rand($image_ids);
        $id = $image_ids[$key];
        $image = wp_get_attachment_image( $id, $size, false, $attr );
    }
    return $image;
}
add_filter( 'woocommerce_product_get_image', 'modify_woocommerce_product_get_image', 99, 4 );



Aucun commentaire:

Enregistrer un commentaire