Autolinking shortcode through articles

Sometimes its hard to crawl through all your articles and link them with specific keywords. What if you could just define the keywords you would like to have linked and Hugo finds the proper keywords and link them automatically with the actual page.

Example

For this case we will create a Shortcode that finds keywords or phrases and link them with found phrases in other markdown files.

Example usage:

some-article.md

+++
date = "2016-10-15T00:04:13+02:00"
publishdate = "2016-10-15T00:04:13+02:00"
draft = false
title = "This is an article about Examples"

# these phrases will be automatically linked with this articles link
seo = ["all about examples", "examples list"]
+++

{{< seo-autolink p>}}This is an Article about examples. Lorem ipsum dolor.{{< /seo-autolink >}}

another-article.md

+++
date = "2016-10-15T00:04:13+02:00"
publishdate = "2016-10-15T00:04:13+02:00"
draft = false
title = "This is another article."

# these phrases will be automatically linked with this articles link
seo = ["Lorem ipsum dolor"]
+++

{{< seo-autolink blockquote>}}This is another article, you can find all about examples including a large examples list in the prior article.{{< /seo-autolink >}}

Will generate the following output:

example.com/some-article/

...
<p>
    This is an Article about examples. <a href="/another-article/">Lorem ipsum dolor.</a>
</p>
...

example.com/another-article/

...
<blockquote>
    This is another article, you can find <a href="/some-article/">all about examples</a> including a large <a href="/some-article/">examples list</a> in the prior article.
</blockquote>
...

So you do not have to think about linking old articles with a certain keyword. This shortcode just does the work for you. You just need to think about SEO relevant linking phrases.


The Shortcode

Create a new file called seo-autolink.html and put it into the layouts/shortcodes/-Folder like this:

|-- layouts
|  |-- shortcodes
|  |  |-- seo-autolink.html

And copy paste the following content into this file:

{{ printf "<%s>" (.Get 0) | safeHTML }}
{{ $.Scratch.Set "content" .Inner }}
{{ range where $.Site.Pages.ByPublishDate.Reverse ".Params.seo" "ne" nil }}
    {{ $tmpPage := . }}
    {{ range .Params.seo }}
        {{ $.Scratch.Set "content" (($.Scratch.Get "content") | replaceRE . (printf "<a href=\"%s\" title=\"%s\">%s</a>" $tmpPage.RelPermalink $tmpPage.Title . ) )  }}
    {{ end }}
{{ end }}
{{ $.Scratch.Get "content" | safeHTML }}
{{ printf "</%s>" (.Get 0) | safeHTML }}

Done. Happy SEO-Linking :-)