Last active
October 15, 2020 14:02
-
-
Save jonleverrier/37027f135c478bc244ae2839ffa04a90 to your computer and use it in GitHub Desktop.
Craft CMS 3 XML Sitemap Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{# | |
Craft CMS 3 Sitemap Example | |
This sitemap example presumes you have some custom fields setup. These are: | |
- contentShowInSitemap | |
- contentSitemapChangeFreq | |
- contentSitemapPriority | |
#} | |
{# | |
Sitemap Configuration | |
#} | |
{% set excludeSections = ['not', 2, 3] %} | |
{% set primarySiteId = 1 %} | |
{# | |
Set varables | |
#} | |
{# Get all entries from primary site, exclude sections we don't want #} | |
{% set siteMap = craft.entries.siteId(primarySiteId).sectionId(excludeSections).all() %} | |
{# Get all sites #} | |
{% set languages = craft.app.sites.getAllSites() %} | |
<?xml version="1.0" encoding="UTF-8"?> | |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/TR/xhtml11/xhtml11_schema.html"> | |
{# For each item in the sitemap #} | |
{% for item in siteMap %} | |
{# If contentShowInSitemap is enabled #} | |
{% if item.contentShowInSitemap != 0 %} | |
<url> | |
<!-- {{ item.title }} --> | |
<loc>{{ item.getUrl() }}</loc> | |
<lastmod>{{ item.dateUpdated|date('Y-m-d\\TH:i:sP') }}</lastmod> | |
<changefreq>{{ item.contentSitemapChangeFreq|default('daily') }}</changefreq> | |
<priority>{{ item.contentSitemapPriority|default('0.5') }}</priority> | |
{# Check if there is a multiligual version available... #} | |
{% for language in languages %} | |
{# ignore results from primary site, as we already have those... #} | |
{% if language.primary != primarySiteId %} | |
{# get results... #} | |
{% set languageItem = craft.entries().id(item.id).siteId(language.id).one() %} | |
{# if there is a translation enabled in the cp... #} | |
{% if languageItem is not null %} | |
<xhtml:link rel="alternate" hreflang="{{language.language}}" href="{{ languageItem.getUrl() }}" /> | |
{% endif %} | |
{% endif %} | |
{% endfor %} | |
</url> | |
{% endif %} | |
{% endfor %} | |
</urlset> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment