9

I want 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.

How can I get product variation images?

3 Answers 3

11

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'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! If you aren't already sure that the product is variable you have to check first (with $product->get_type() for instance), or the method get_available_variations() might not exist.
5

For Woocommerce 3. loop over like this once you create the variations array.

foreach ( $variations as $variation ) {
    echo $variation['image']['url'];
}

3 Comments

This grabs the original image - how would you grab the thumbnail? Or any other size for that matter?
This has been answered by @Elvin85 here: link
This 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']
-1

in functions file

add_action('woocommerce_after_shop_loop_item_title','woocommerce_template_single_excerpt', 5);
function woocommerce_template_single_excerpt() {
            global $product;
            if ($product->product_type == "variable" && (is_shop() )) {
              echo woocommerce_variable_product(); 
            }

 }

1 Comment

The 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.