Display first image in post in link preview

I’d like to display the first image in my blog post in the preview that is created when linking to a post. Here is an example of a link preview that fails to do this: https://plus.google.com/114020196546350685241/posts/AkUKgogAmg7

What do I need to do to make this work?

I’m guessing you are talking about open graph tags. You need to have meta tags on the section of your html.

It looks like this
<meta property="og:image" content="{{ .Site.BaseURL}}images/logo.png" />

If you want to ‘fetch’ the first image you can do something like this:

	{{ with .Params.images }}
		{{ range first 1 . }}
	<meta property="og:image" content="{{ . | absURL }}" />
		{{ end }}
	{{ end }}

I didn’t test it, but i think it was working on a previous installment of my blog.

1 Like

I’m sorry, but I didn’t understand very much of that. Are you saying that code goes in a partial?

I don’t know what a graph tag is.

I’m trying to display the first image from a post (not from my main page) whenever I share link, if that’s possible.

The Open Graph tags are what Facebook and other social networks use to display link previews. You have more information here: http://ogp.me/

And yes, that bit of code goes into the head of your single.html or a partial that is loaded in that section.

Note that Hugo ships with an internal opengraph template too. If you would like to use that, add below in the HTML head in your layout:

{{ template "_internal/opengraph.html" . }}

On similar notes, there’s twitter_cards.html internal template too.



You’re saying both pieces of code go in the head? Why did you split them up in your description?

Hi were you able to achieve this? also having the same problem i already included hugo internal opengraph and twitter card partials in the head partial.

It’s not clear who you are addressing, or what’s the “same problem” :slight_smile:

But in any case, I solved the issue of translating relatives links in images front-matter to absolute links in the opengraph meta tags using my custom template opengraph.html (and the same fix in twitter_cards.html).

Yeah I was referring to @valzi sorry I didn’t state that I also just solved mine by adding Hugo internal opengraph.html and twitter_cards.html and fix from Hugo Fix for Facebook OpenGraph og:image not pulling images