Ability to use --buildDrafts but exclude them from sitemap

I would like to render drafts while they are being written but keep them from appearing in sitemap.xml.
Is that possible?

Yes. Override the built-in sitemap template.

See https://gohugo.io/templates/sitemap-template/#overview.

1 Like

Cheers, beautiful solution.
For people who might find this thread in the future looking for the solution.

Run hugo --buildDrafts

Inside your theme folder layouts/_default/sitemap.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 (and (.Permalink) (not .Draft)) -}}
  <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>

And probably it’s a good idea to add meta noindex tag to your template as well

  {{ if .Params.Draft }}
    <meta name="robots" content="noindex" />
  {{ end }}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.