Update: Sitemap support was officially added in Ghost 0.5.6, so this tutorial is now obsolete.
The release of Ghost 0.5.0 included changes to some core functionality that breaks compatibility with my friend's dynamic sitemap tutorial. With sitemap support likely to be a 0.6.0 feature, here's how you can get it working in 0.5.0 in the meantime. I'm going to assume that you're starting with a fresh copy of 0.5.0, or even 0.5.1-1.
In /core/server/routes/frontend.js, add an entry for the sitemap.xml url:
frontendRoutes = function () {
var router = express.Router(),
subdir = config.paths.subdir;
// ### Frontend routes
router.get('/sitemap.xml/', frontend.sitemap);
router.get('/rss/', frontend.rss);
...
}
In /core/server/controllers/frontend.js, there are three areas to update.
1) Add a reference to the sitemap
module:
var moment = require('moment'),
RSS = require('rss'),
_ = require('lodash'),
url = require('url'),
when = require('when'),
sm = require('sitemap'),
...
2) The buildSitemap
method is mostly the same, but I've included the base url with the highest priority, and made the proper call to the config
object (no parentheses):
function buildSitemap(posts, done, sitemap) {
var sitemap = sitemap || sm.createSitemap({
hostname: config.url,
cacheTime: 600000
});
if (posts.length > 0) {
var post = posts.shift();
// Give static pages a higher priority
sitemap.add({ url: '/' + post.slug + '/', priority: post.page == 0 ? 0.5 : 0.8 });
process.nextTick(buildSitemap.bind(this, posts, done, sitemap));
}
else {
// Base url
sitemap.add({ url: '/', priority: 1, changefreq: 'daily' });
done(sitemap);
}
}
3) Add the same sitemap
item to the frontendControllers
object:
frontendControllers = {
'sitemap': function(req, res, next) {
api.posts.browse({ staticPages: 'all', limit: 1000 }).then(function(result) {
buildSitemap(result.posts, function(sitemap) {
sitemap.toXML(function(xml) {
res.header('Content-Type', 'application/xml');
res.send(xml);
});
});
});
},
Finally, in /packages.config, add an entry for sitemap:
"dependencies": {
"bcryptjs": "0.7.10",
...
"xml": "0.0.12",
"sitemap": "~0.7.3"
},
I got this to work in 0.5.0 and 0.5.1-1, but this may not work in future 0.5+ releases, and will certainly be unnecessary when sitemap support is native. I'm working on another modification for this to include tags and authors. Before I get to that, I'm going to write up a tutorial for multi-level URLs, something I'm using now throughout my site.