FROM CACHE - en_header

How to get 'image.attached_to_variant?' to work on the media object.

Chulee0606
New Member
2 0 2

Hi, 

I'm trying to hide the variant images from the product thumbnails below the main image. Normally I would use 'image.attached_to_variant?' to check and hide them, but because the newer themes are using the media object. instead of image, to support new types of medias, this doesn't work according to Shopify documentation. Does anyone know how to achieve the same result with the media object? 

Screen Shot 2020-09-16 at 9.34.41 AM.png

 

Replies 4 (4)
davidhollenbeck
Shopify Partner
12 0 1

Hey Chulee, did you ever get this working?

ryan99
Shopify Partner
13 1 3

The simplest solution I've found is to build an array of the images attached to variants and then reference that within the loop:

 

{%- assign variant_images = product.images | where: 'attached_to_variant?', true | map: 'src' -%}
{%- if product.media.size > 1 -%}
    {%- for media in product.media -%}
       {%- if variant_images contains media.src -%}
           ... do what you need to do with the variant images
       {%- endif -%}
       ... do whatever else you need to do
   {%- endfor -%}
{%- endif -%}   

 

Since the the only media type that can be attached to variants is images you won't risk missing any. `{{media.src}}` seems to be the most reliable way to match since the id's very under different circumstances.

Christopotamus
New Member
1 0 2

Absolutely insane that we have to resort to this... but it works great. I imagine if you have a lot of products being displayed with lots of different variant images, this will slow things down a lot, but I guess it's probably one of the only ways to do it without an external app, which may end up being even slower

Rennes
Shopify Partner
1 0 0

So, years later... I ran into basically the same problem, just from the angle of trying to match variant.image objects to entries in the product.media array instead of product.images like I'd previously done.

 

In the past I used variant.image.id to match up with a given product img.id, but the ID properties are different when accessing images in the media array rather than the images array.  I tried to convince Shopify this was a bug in the API since you would think the ID should be the same, or at least there should be some way of getting to the same ID, but they said tough luck, we won't talk to you if you're making your own theme, go check the forums or hire an "expert."

 

So, I ended up using the src property instead like Ryan99 suggested.  Works fine, but still pretty stupid that it's needed, and that Shopify refuses to even take a look.  (If you ever read these, Shopify, please spend less time on 3D spinning globes in the analytics and more time making your existing stuff less buggy.)