In this blog I will guide you how you can fetch the sitemaps from WordPress and show it in Next.js .
When migrating from WordPress to Next.js we face issues while generating sitemaps because WordPress does not provide any rest api for us to get the posts , pages, categories links in a systematic format.
In WordPress we use some plugins to generate the sitemaps, one of that plugin is RankMath.
The RankMath plugin create separates routes for XML sitemaps,
/sitemap_index.xml
/post-sitemap.xml
/page-sitemap.xml
/category-sitemap.xml
In Next.js we will use the getServerSideProps
function to fetch these sitemaps on the server
Let's begin
Download the static files from github link
Edit Files in the sylesheets and add your name and url at required places.
Save these files to
public
directory.In
.env
file add NEXT_PUBLIC_WP_CMS_URL variable and make it equal toyour_wordpress_site_url.com
Create a file in the directory called
pages/sitemap/[slug].tsx
.
Now in the sitemap/[slug].tsx
enter the following codes.
import { GetServerSideProps } from "next";
export default function Sitemap( ) {
return (
<>
</>
);
}
export const getServerSideProps: GetServerSideProps = async ({
res,
params,
}) => {
const { slug } = params!;
if (slug && slug.includes(".xml")) {
const url = process.env.NEXT_PUBLIC_WP_CMS_URL + `/${slug}`;
const resp = await fetch(url).then((r) => r.text());
let format = resp
.replace(`//www.your_wordpress_site.com/news-sitemap.xsl`, "/v.xsl")
.replace("//www.your_wordpress_site.com/main-sitemap.xsl", "/main-sitemap.xsl")
.replace(
"//www.your_wordpress_site.com/video-sitemap.xsl",
"/video-sitemap.xsl"
)
.replaceAll(`www.your_wordpress_site.com.com`, "www.your_next_js_site.com")
res.setHeader("Content-Type", "text/xml");
res.write(format);
res.end();
return {
props: {},
};
} else {
return {
props: { },
notFound:true
};
}
};
I hope this helps if you get stuck at any place let me know , I would love to help you.
Top comments (0)