Skip to content

Instantly share code, notes, and snippets.

Last active July 9, 2022 14:54
Show Gist options
  • Save urlsangel/70f2b6a7fe46ee8a6133536a76caf48f to your computer and use it in GitHub Desktop.
Save urlsangel/70f2b6a7fe46ee8a6133536a76caf48f to your computer and use it in GitHub Desktop.
Google-friendly sitemaps for multilingual Wagtail sites
from wagtail.models import Page
from translation.utils import get_translated_sitemap_urls
class ExtendedPage(Page):
class Meta:
abstract = True
def get_sitemap_urls(self, request):
page = self.localized
default_data = [{
'location': page.full_url,
'lastmod': (page.last_published_at or page.latest_revision_created_at),
return get_translated_sitemap_urls(page, request, default_data)
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="" xmlns:xhtml="">
{% spaceless %}
{% for url in urlset %}
<loc>{{ url.location }}</loc>
{% if url.lastmod %}
<lastmod>{{ url.lastmod|date:'Y-m-d' }}</lastmod>
{% endif %}
{% for item in url.alternates %}
<xhtml:link rel="alternate" hreflang="{{ item.locale.language_code }}" href="{{ item.url }}"/>
{% endfor %}
{% endfor %}
{% endspaceless %}
# Amend these to the domains your translated site uses
'en': '',
'fr': '',
'es': '',
def get_translatable_page_siblings(instance, only_live=True, include_self=False):
translations = instance.get_translations(inclusive=include_self)
if only_live:
translations =
return translations
def get_translated_sitemap_urls(page, request, default_data):
host = request.get_host()
domain = None
lang = None
for k, v in domains.items():
if v == host:
domain = v
lang = k
if domain and lang:
# return empty array if this page isn't the current language
if page.locale.language_code != lang:
return []
# get default sitemap data for page, return if no data
data = next(iter(default_data))
if not data:
return []
# get self and siblings, add to data and return
siblings = get_translatable_page_siblings(page, only_live=True, include_self=True).select_related('locale')
data['alternates'] = siblings
return [data]
# return an empty array if none of the above
return []
Copy link

To implement:

  • sitemap.xml should be placed in the root of any included templates folder, e.g templates/sitemap.xml
  • ExtendedPage should be used as an inherited mixin to all of your Wagtail pages
  • can be placed anywhere, e.g. translation/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment