Refer to this for the original article.
While building this site, I wanted to create a sitemap for it.
A sitemap is an XML file that tells search engines like Google about all the pages on your site.
Creating one in Statamic is relatively easy.
Step 1: Creating the sitemap template
First, we need to create a template for our sitemap. In Statamic, templates live in the /resources/views folder. Let’s create a new file there called sitemap.antlers.html.
Here’s the code you’ll add to that file:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{{ collection:pages }}
<url>
<loc>{{ permalink }}</loc>
<lastmod>{{ last_modified format="Y-m-d" }}</lastmod>
<changefreq>weekly</changefreq>
<priority>{{ if url == homepage }}0.8{{ else }}0.5{{ /if }}</priority>
</url>
{{ /collection:pages }}
</urlset>
Let’s break this down:
-
<urlset>
: This is the root element for the sitemap. -
{{ collection:pages }}: This loops through all the pages in your pages collection (you can replace pages with any collection you want to include).
-
<loc>
: This is the full URL of the page. -
<lastmod>
: This shows the last modified date of the page. -
<changefreq>
: This tells search engines how often the page is updated (e.g., weekly). -
<priority>
: This sets the priority of the page. The homepage usually gets a higher priority (0.8), while other pages get a lower priority (0.5).
Step 2: Add a Route for the Sitemap
Next, we need to tell Statamic where to find this sitemap. Open your /routes/web.php
file and add the following code:
Route::statamic('sitemap.xml', 'sitemap', [
'layout' => 'sitemap',
'content_type' => 'xml'
]);
Step 3: Test your sitemap
Done!.
Now, visit {{url}}/sitemap.xml
in your browser, and you should see your shiny new sitemap.
If everything looks good, you can submit it to Google Search Console or other search engines to help them crawl your site more effectively.
Bonus tips:
- Include Other Collections: If you have other collections (like blogs, projects, posts, etc), you can loop through them in the same template. Just add another {{ collection:your_collection }} block.
I added this for my blogs and projects.
-
Dynamic Updates: Since Statamic automatically updates your content, your sitemap will always stay up-to-date. No manual work required!
-
Customize Priority and Frequency: Feel free to tweak the
<priority>
and<changefreq>
values based on how important or frequently updated your pages are.