Code Shopify About

Shopify App and Theme Development tutorials for those who are familiar with code and want to dive into Shopify.

Sign up for Shopify

How to use Images from Metafields in Shopify Liquid

Friday, Dec 02, 2022

Shopify has made our lives so much easier by providing new metafields that can be added right on the product admin page and they've also given us a whole bunch of metafield types. This is great 🎉. However, it's not always clear how to access all the data you're interested in. In this post we're going to be going over how to use the Image Metafield.

Accessing Metafields

In general, you access metafields by the object they're associated to (ex. Product) then reference metafields, then the namespace and the value. By default, Shopify gives the namespace custom.


For example, it could look something like this if you name your metafield Lifestyle Image.

{{ product.metafields.custom.lifestyle_image }}

Image Metafield attributes

The following code produces the gid something like gid://shopify/MediaImage/1111111111 which you would use for a graphql call.

{{ product.metafields.custom.lifestyle_image }}

We use value to get the relative url in liquid. You'll get something like this files/image_name.png

{{ product.metafields.custom.lifestyle_image.value }}

Working with the image_url filter

You might be wondering, if I just get the url of the image, how do I access all the other properties that I normally get with, say, a product image?

Well, it's a little counterintuitive, but you can access the image attributes by appending the attribute after .value. For example, you can access the image width and height like this:

	{{ product.metafields.custom.lifestyle_image.value.width }}
	{{ product.metafields.custom.lifestyle_image.value.height }}

You won't be able to access the attributes directly associate with a product even though, in this case, the metafield is on the product.

The one main thing missing, is there doesn't seem to be a way to add alt text to the image, however, when there is a way, presumably you'd be able to access it like so.

{{ product.metafields.custom.lifestyle_image.value.alt}}

Using the metafield with the image_url filter

You'll also still be able to take advantage of the image_url filter, but adding the metafield definition plus the value attribute 🎉🎉

{{ product.metafields.custom.lifestyle_image.value  | image_url: width: 400 | image_tag: loading: 'lazy' }}
more posts