Reputation: 603
I'm using the following code to grab the image of every variation for a particular product:
$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
echo "<img src=" . $variation['image']['url'] .">";
}
This returns the full size image.
Can anyone tell me how I would modify this to return the 'thumbnail' URL? (or any other size)
I'm sure it's a fairly simple change but I just can't figure it out.
Upvotes: 6
Views: 19088
Reputation: 2192
Since WooCommerce version 3.0.0 you can get the ID of a variation image as:
$image_id = $variation->get_image_id();
This will return the variation image ID if available, otherwise, the main product image ID will be returned. A variation image could be found in the product back-end as in the image below:
You can then use this image ID to get the URL to your variation or product thumbnail image as:
$image_array = wp_get_attachment_image_src($image_id, 'thumbnail');
$image_src = $image_array[0];
The code snippet is tested and working.
Upvotes: 4
Reputation: 41
i have different colors and sizes of clothing. Is it possible to omit the size and only show the thumbnail of a single color
Right now, it is showing thumbnails for color red in small, medium, and large size. Three duplicated thumbnails.
Upvotes: 0
Reputation: 1421
If you know the product variation ID, you can do
// find out $variation_id, it's different from product_id
$variation = new WC_Product_Variation( $variation_id );
$image_tag = $variation->get_image();
// The below is the whole image tag including <img> and some classes that will help customize it.
echo $image_tag;
See related docs found at the Woocommerce reference for WC_product_variation class and the WC_Product class. The function get_image() is actually inherited from WC_Product, but you can use it in either class.
Upvotes: 4
Reputation: 3572
Use thumb_src instead of url.
$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
echo "<img src=" . $variation['image']['thumb_src'] .">";
}
Upvotes: 5