Get product variation images on Woocommerce shop page
26,479
Solution 1
You can get a list of the product's variations:
// In the product loop:
$variations = $product->get_available_variations();
// Outside the product loop:
$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();
Loop over it to get the image from each variation like so:
foreach ( $variations as $variation ) {
echo $variation['image_src'];
}
Solution 2
For Woocommerce 3. loop over like this once you create the variations array.
foreach ( $variations as $variation ) {
echo $variation['image']['url'];
}
Author by
Admin
Updated on July 22, 2022Comments
-
Admin almost 2 years
What I essentially want to achieve is to show product variation images (particular image for each variation) on the shop page. I was successfully able to get the name of the variations using the code below (put into "content-product.php"):
<?php $colourvalues = get_the_terms( $product->id, 'pa_colour'); foreach ( $colourvalues as $colourvalue ) { echo $colourvalue->name; } ?>
Unfortunately there is nothing in the
$colouvalues
array that is the variations image url or anything related to the image.Does anyone please help me with this?
-
NuclearApe over 6 yearsThis grabs the original image - how would you grab the thumbnail? Or any other size for that matter?
-
NuclearApe over 6 yearsThis has been answered by @Elvin85 here: link
-
Tofandel over 4 yearsThis is only for the thumbnail, for other sizes you can get the attachment id and then use wordpress functions to handle attachments using $variation['image_id']
-
Punchlinern about 3 yearsGreat! If you aren't already sure that the product is variable you have to check first (with
$product->get_type()
for instance), or the methodget_available_variations()
might not exist. -
brett about 2 yearsThe provided code is not related to the question (it does not retrieve the variation image as asked). Moreover there's no built-in function called woocommerce_variable_product() in Woocommerce or WP. As it stands, this looks like a random copy paste from a functions.php file of a custom theme.