XML-sitemap in Jekyll

How to easily generate a XML-sitemap in Jekyll without any plugins.

Generating a dynamically updated sitemap according to sitemaps.org protocol in Jekyll extremely easy without any plugins.

All of the credits go to Daviden Singer exellent post on building a better sitemap with Jekyll, which is 95% copied below. I just made a small tweak, changing unless post.published == false to unless post.published == false or post.sitemap.exclude == "yes" so also post can be excluded.

1. Create a XML-file

Create a new file with the XML-extension into root folder called sitemap.xml.

2. Generate XML-sitemap

Simply add the following code:

---
layout: null
sitemap:
  exclude: 'yes'
---
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  {% for post in site.posts %}
    {% unless post.published == false %}
    <url>
      <loc>{{ site.url }}{{ post.url }}</loc>
      {% if post.sitemap.lastmod %}
        <lastmod>{{ post.sitemap.lastmod | date: "%Y-%m-%d" }}</lastmod>
      {% elsif post.date %}
        <lastmod>{{ post.date | date_to_xmlschema }}</lastmod>
      {% else %}
        <lastmod>{{ site.time | date_to_xmlschema }}</lastmod>
      {% endif %}
      {% if post.sitemap.changefreq %}
        <changefreq>{{ post.sitemap.changefreq }}</changefreq>
      {% else %}
        <changefreq>monthly</changefreq>
      {% endif %}
      {% if post.sitemap.priority %}
        <priority>{{ post.sitemap.priority }}</priority>
      {% else %}
        <priority>0.5</priority>
      {% endif %}
    </url>
    {% endunless %}
  {% endfor %}
  {% for page in site.pages %}
    {% unless page.sitemap.exclude == "yes" %}
    <url>
      <loc>{{ site.url }}{{ page.url | remove: "index.html" }}</loc>
      {% if page.sitemap.lastmod %}
        <lastmod>{{ page.sitemap.lastmod | date: "%Y-%m-%d" }}</lastmod>
      {% elsif page.date %}
        <lastmod>{{ page.date | date_to_xmlschema }}</lastmod>
      {% else %}
        <lastmod>{{ site.time | date_to_xmlschema }}</lastmod>
      {% endif %}
      {% if page.sitemap.changefreq %}
        <changefreq>{{ page.sitemap.changefreq }}</changefreq>
      {% else %}
        <changefreq>monthly</changefreq>
      {% endif %}
      {% if page.sitemap.priority %}
        <priority>{{ page.sitemap.priority }}</priority>
      {% else %}
        <priority>0.3</priority>
      {% endif %}
    </url>
    {% endunless %}
  {% endfor %}
</urlset>

3. Add Front Matter to posts/pages (Optinal)

Now we can add the following optional Front Matter markup to posts and pages

---
layout: post
title:  "Hello world!"
date:   2018-01-01 16:16:01 -0600
sitemap:
  lastmod: 2018-01-02
  priority: 0.7
  changefreq: 'monthly'
  exclude: 'yes'
---

Per default all post and pages will get changefreq monthly, pages gets priority 0.5 while posts get 0.3.

Dela på Facebook