Missing article image on Twitter due to GetMatch in Hugo template
Recently I received notification that somebody post information about my article on Twitter (thanks!). Twitter usually renders a link to blog posts as nice-looking cards. The card to my article shown up without a featured image.
I checked my Twitter feed, and some of my other entries also suffer from missing featured images.
After checking some of my articles in Twitter’s Card Validator, It turned out that some of them have missing metadata that twitter needs to render the cover image.
I found that my theme uses Hugo’s internal template to render Twitter’s metadata. Unfortunately, nothing within the template gave me an answer at first glance. I found out that to render twitter:image
metadata correctly, there must be an image with feature, cover, or thumbnail in the filename. I follow this convention, even though I didn’t know about it.
Articles that have missing cover have one in common. Since I use Page Bundles, after migrating from WordPress to Hugo, I put images in the directory called images
for each article.
As you see carefuly, there is a problem with GetMatch
function used in the template. Let’s look at the following code:
{{- $featured := $images.GetMatch "*feature*" -}}
{{- if not $featured }}{{ $featured = $images.GetMatch "{*cover*,*thumbnail*}" }}{{ end -}}
According to the Hugo documentation, this specific usage of GetMatch
will work only for files in the root of each Page Bundle. The path images/featured.jpg
doesn’t match the *feature*
pattern.
So I moved featured images to the root of each post directory. Now, my old articles have started rendering proper metadata, giving Twitter enough data to display the cover image on the feed.