Sitemap for search engines

Hello,

I am setting up a simple sitemap following the Cookbook. The site is based on a plainkit installation. So, I manually created a config folder and a config.php file: site/config/config.php. I pasted the following code into the config.php:

<?php

'routes' => [
  [
    'pattern' => 'sitemap.xml',
    'action'  => function() {
        $pages = site()->pages()->index();

        // fetch the pages to ignore from the config settings,
        // if nothing is set, we ignore the error page
        $ignore = kirby()->option('sitemap.ignore', ['error']);

        $content = snippet('sitemap', compact('pages', 'ignore'), true);

        // return response with correct header type
        return new Kirby\Cms\Response($content, 'application/xml');
    }
  ],
  [
    'pattern' => 'sitemap',
    'action'  => function() {
      return go('sitemap.xml', 301);
    }
  ]
]

?>

I created sitemap.php in site/snippets with:

<?= '<?xml version="1.0" encoding="utf-8"?>'; ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php foreach ($pages as $p): ?>
        <?php if (in_array($p->uri(), $ignore)) continue ?>
        <url>
            <loc><?= html($p->url()) ?></loc>
            <lastmod><?= $p->modified('c', 'date') ?></lastmod>
            <priority><?= ($p->isHomePage()) ? 1 : number_format(0.5 / $p->depth(), 1) ?></priority>
        </url>
    <?php endforeach ?>
</urlset>

When calling sitemap.xml, I get a blank white page, an empty sitemap. Did I miss anything?

I got it. The code for the config.php must be:

<?php

return [
  'routes' => [
    [
      'pattern' => 'sitemap.xml',
      'action'  => function() {
          $pages = site()->pages()->index();
  
          // fetch the pages to ignore from the config settings,
          // if nothing is set, we ignore the error page
          $ignore = kirby()->option('sitemap.ignore', ['error']);
  
          $content = snippet('sitemap', compact('pages', 'ignore'), true);
  
          // return response with correct header type
          return new Kirby\Cms\Response($content, 'application/xml');
      }
    ],
    [
      'pattern' => 'sitemap',
      'action'  => function() {
        return go('sitemap.xml', 301);
      }
    ]
  ]
];
2 Likes

Just followed the cookbook and found the same error. It would be nice to have de cookbook fixe @bastianallgeier

I just fixed it on our site. We often leave out the leading PHP tag to simplify examples, but I get that it’s often confusing.

You can also always send us a PR on Github for such fixes if you want: GitHub - getkirby/getkirby.com: Source code and content for the Kirby website

1 Like