Let's have a look at adding a sitemap to your Wagtail website. We can use the Django sitemap app to add one. As usual, we first start with adding it to the list of installed apps in our settings:

mysite/settings/base.py

INSTALLED_APPS = [
    ...
    'django.contrib.sitemaps',
    ...
]

To finish the installation, we also need to add the URL definitions to url.py:

mysite/urls.py

from wagtail.contrib.sitemaps.views import sitemap

urlpatterns = [
    ...
    path('sitemap.xml', sitemap),
    ...
    # Ensure that the 'sitemap' line appears above the default Wagtail page serving route
    re_path(r'', include(wagtail_urls)),
]

That's all you need to do to get it up and running. If you now browse to "/sitemap.xml" on your site, it will return the proper file based on the structure of your site.

You can customize the list of URLs which is included for a page in the sitemap by implementing the get_sitemap_urls function:

In my blog, I only want to include the BlogPost objects which have a publish date which is not empty and is older than today. I've set it up like this:

class BlogPost(Page):
    def get_sitemap_urls(self, request):
        if not self.date or self.date > timezone.now():
            return []
        return super(BlogPost, self).get_sitemap_urls(request)

When you return an empty list, it will not include the page in the sitemap.

You can find more info in the Wagtail documentation.

Related Posts

  • Defining custom settings in Wagtail
  • Making publish the default action in Wagtail
  • Migrating your Wagtail site to a different database engine
  • Programatically creating redirects in Wagtail
  • Change the Wagtail site domain via a management command