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
1INSTALLED_APPS = [
2 ...
3 'django.contrib.sitemaps',
4 ...
5]
To finish the installation, we also need to add the URL definitions to url.py
:
mysite/urls.py
1from wagtail.contrib.sitemaps.views import sitemap
2
3urlpatterns = [
4 ...
5 path('sitemap.xml', sitemap),
6 ...
7 # Ensure that the 'sitemap' line appears above the default Wagtail page serving route
8 re_path(r'', include(wagtail_urls)),
9]
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:
1class BlogPost(Page):
2 def get_sitemap_urls(self, request):
3 if not self.date or self.date > timezone.now():
4 return []
5 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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.