My Work Notes

29 Dec 2022

Custom sitemap in Hugo with exclude option

Put under themes/<your-theme-name>/layouts/_default a new file with a custom sitemap template named stitemap.xml:

{{  printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" | safeHTML }}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
    {{  range .Data.Pages }}
    {{-     if or (eq (isset .Params "sitemapexclude") false) (ne .Params.sitemapExclude true) }}
    <url>
        <loc>{{ .Permalink }}</loc>{{ if not .Lastmod.IsZero }}
        <lastmod>{{ safeHTML ( .Lastmod.Format "2006-01-02T15:04:05-07:00" ) }}</lastmod>{{ end }}{{ with .Sitemap.ChangeFreq }}
        <changefreq>{{ . }}</changefreq>{{ end }}{{ if ge .Sitemap.Priority 0.0 }}
        <priority>{{ .Sitemap.Priority }}</priority>{{ end }}{{ if .IsTranslated }}{{ range .Translations }}
        <xhtml:link
                rel="alternate"
                hreflang="{{ .Language.Lang }}"
                href="{{ .Permalink }}"
        />{{ end }}
        <xhtml:link
                rel="alternate"
                hreflang="{{ .Language.Lang }}"
                href="{{ .Permalink }}"
        />{{ end }}
    </url>
    {{-     end }}
    {{  end }}
</urlset>

Then use sitemapExclude: True in the front matter of the page you want to exclude from the sitemap.