How to get width/height of external image via liquid

mfcss
Explorer
54 6 13

I'm trying to create a script to dynamically extract a specific image URL from my page.content and use it in the social sharing og:image fields.

 

The purpose is to avoid having to display the "default" image for all my Pages. 

 

I have the liquid code in place for extracting my URL from my page.content. However, I also need to provide the image width/height in order for the social sharing image to be displayed as intended. 

 

my question: Is there a way to use Liquid to extract the width/height of an image via the image URL?

Replies 5 (5)
DMT-Mat
Shopify Partner
15 2 12

If you already have the image extracted and stored as a liquid variable, {{ your_image.width }} and {{ your_image.height }} should output the width and height values - you should be able to use those to inject the values into the html.

Need expert help with your Shopify Website? Message me or contact the team.
mfcss
Explorer
54 6 13

Thanks - I'm able to extract the URL, but I guess it's a text string. How do I convert the URL text string into an image variable in liquid?

DMT-Mat
Shopify Partner
15 2 12

It really depends on your set up but you could use liquid filters:

{{ your_image | image_url: width: 500, height: 500 }} may work with your variable?

Need expert help with your Shopify Website? Message me or contact the team.
mfcss
Explorer
54 6 13

Thanks - the challenge is that it may differ page-by-page what the width/height dimensions are for the image. I'd ideally like a dynamic way to extract the information about width/height from an external image URL via Liquid. Once I have done this, I could then provide them via an image variable (as per your example) or directly into the relevant fields for social sharing, i.e. as below:

 

<meta property="og:image" content="{{url}}">
<meta property="og:image:secure_url" content="{{url}}">
<meta property="og:image:width" content="{{width}}">
<meta property="og:image:height" content="{{height}}">
DMT-Mat
Shopify Partner
15 2 12

Hmm I'm not sure if that's possible yet with liquid. I've browsed the forums but only solutions to do this need JS on pageload, which doesn't really help in your situation.

 

If these values absolutely have to be dynamic I think the only option is to leave out the og:image:width and height lines, which may have a minor performance impact but likely a better option than explicitly setting them as a fixed size.

Need expert help with your Shopify Website? Message me or contact the team.