Automatic Open Graph & Twitter Image from the 1st image found in a Page Bundle

For those of you who may want to render the 1st image found in a Page Bundle as an Open Graph & Twitter image:

{{ with (index (.Resources.ByType "image") 0) -}}
{{- $image := . -}}
{{- $image = $image.Fill "1200x630" -}}
 <meta property="og:image" content="{{ $image.Permalink }}"/>
 <meta property="og:image:secure_url" content="{{ $image.Permalink }}"/>
 <meta property="og:image:width" content="{{ $image.Width }}"/>
 <meta property="og:image:height" content="{{ $image.Height }}"/>
 <meta name="twitter:image:src" content="{{ $image.Permalink }}"/> 
 {{- else -}}
 <meta property="og:image" content="{{ site.Params.og_image | relURL }}"/>
 <meta property="og:image:secure_url" content="{{ site.Params.og_image | absURL }}"/>
 <meta name="twitter:image:src" content="{{ site.Params.og_image | absURL }}"/>
{{- end }}

In the above I am using the dimensions 1200x630 pixels for the cropped image as these are currently recommended for Open Graph Images -at least this year-.

If no Page Bundle is found then the Open Graph & Twitter images will be published from a og_image parameter in the project `config.

6 Likes