Created
July 25, 2023 07:34
-
-
Save riccardodicurti/d41bc4b924e998d97973c9d23b28bc03 to your computer and use it in GitHub Desktop.
sitemap.js
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
import { getWPUrl, removeSourceUrl } from '@headstartwp/core'; | |
import { usePosts } from '@headstartwp/next'; | |
function generateSiteMap( posts ) { | |
const host_url = process.env.HOST_URL; | |
return `<?xml version="1.0" encoding="UTF-8"?> | |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> | |
${posts.map(( { loc, lastmod } ) => { | |
return `<url> | |
<loc>${host_url}${loc}</loc> | |
<lastmod>${lastmod}</lastmod> | |
</url>`; | |
}).join('')} | |
</urlset>`; | |
} | |
function SiteMap() { | |
} | |
export async function getServerSideProps( context ) { | |
const postsData = await usePosts.fetcher().get({ postType: 'post', per_page: 50 }); | |
const pagesData = await usePosts.fetcher().get({ postType: 'page', per_page: 50 }); | |
let data = Array.prototype.concat( postsData.result, pagesData.result ); | |
data = data.map(({ link, modified_gmt }) => { | |
return { | |
loc: removeSourceUrl({ link, backendUrl: getWPUrl() }), | |
lastmod: modified_gmt, | |
} | |
}); | |
const sitemap = generateSiteMap( data ); | |
context.res.setHeader('Content-Type', 'text/xml'); | |
context.res.write( sitemap ); | |
context.res.end(); | |
return { | |
props: {}, | |
}; | |
} | |
export default SiteMap; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment