Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Created September 13, 2021 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanmaslyn/e30e7ae0910997a3e2da8fa97759c368 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/e30e7ae0910997a3e2da8fa97759c368 to your computer and use it in GitHub Desktop.
Example sitemap sync from WP to NextJS
import { GetServerSidePropsContext } from "next";
const defaultWpUrl = 'https://example.wpengine.com';
const localHost = 'localhost:3000';
const prodHost = 'example.com';
export default function Sitemap () {};
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
let wpUrl = process.env.NEXT_PUBLIC_WORDPRESS_URL ?? defaultWpUrl;
if (wpUrl?.endsWith('/')) {
wpUrl = wpUrl.substr(0, wpUrl.length - 1);
}
const { hostname } = new URL(wpUrl);
const clientHost = process.env.NODE_ENV === 'development' ? localHost : prodHost;
const xmlRes = await fetch(wpUrl + context.req.url);
let xml = (await xmlRes.text());
// change server locations to client loctions
xml = xml.replace(new RegExp(hostname, 'g'), clientHost);
// change client locations for images back to server locations
xml = xml.replace(new RegExp(`${clientHost}/wp-content/uploads`, 'g'), `${hostname}/wp-content/uploads`);
context.res.setHeader('Content-Type', 'text/xml');
context.res.write(xml);
context.res.end();
return {
props: {}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment