Skip to content

docs: Create a custom WordPress sitemap with custom WP-GQL endpoint #121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 23 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/next/custom-sitemap-apollo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
example-app/package-lock.json
package-lock.json
wp-env/__MACOSX
25 changes: 25 additions & 0 deletions examples/next/custom-sitemap-apollo/.wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"phpVersion": "7.4",
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
"https://github.com/AdvancedCustomFields/acf/releases/download/6.3.12/advanced-custom-fields-6.3.12.zip",
"https://github.com/wp-graphql/wpgraphql-acf/releases/latest/download/wpgraphql-acf.zip",
"https://github.com/wpengine/hwptoolkit/raw/refs/heads/main/examples/next/custom-sitemap-apollo/hwpt-wpgraphql-sitemap.zip"
],
"config": {
"WP_DEBUG": true,
"SCRIPT_DEBUG": false,
"GRAPHQL_DEBUG": true,
"WP_DEBUG_LOG": true,
"WP_DEBUG_DISPLAY": false,
"SAVEQUERIES": false
},
"mappings": {
"db": "./wp-env/db",
"wp-content/uploads": "./wp-env/uploads",
".htaccess": "./wp-env/setup/.htaccess"
},
"lifecycleScripts": {
"afterStart": "wp-env run cli -- wp plugin update wpgraphql-acf && wp-env run cli -- wp rewrite structure '/%postname%/' && wp-env run cli -- wp rewrite flush"
}
}
130 changes: 130 additions & 0 deletions examples/next/custom-sitemap-apollo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Example: Create a custom WordPress sitemap with WPGraphQL and Apollo Client

## Overview

This example demonstrates how to generate a custom sitemap in a headless WordPress application using the Next.js framework. The example app fetches data from WordPress using Apollo Client and WPGraphQL. Since WPGraphQL doesn't support sitemaps natively, we are extending it with a custom plugin, which is included in this example as well. This plugin exposes new fields to fetch the sitemap index, with data identical to what's rendered on the native WordPress sitemap. Another field exposed by this plugin allows you to request sitemap subpages by specifying the types and pages. The plugin also adds featured image data, enabling you to create [Image Sitemaps](https://developers.google.com/search/docs/crawling-indexing/sitemaps/image-sitemaps).

The example includes a wp-env setup, which will allow you to build and start this example quickly. With this wp-env setup, you don't need to have a separate WordPress instance or demo data to inspect the example.

## Features

1. Fetching sitemap data with the API allows maximum customizability
2. Custom plugin to extend WPGraphQL with the sitemap feature
3. Plugin uses native WordPress sitemap hooks and methods for security and performance
4. An identical WordPress sitemap structure in the headless setup
5. [Image Sitemaps](https://developers.google.com/search/docs/crawling-indexing/sitemaps/image-sitemaps) implementation
6. Configured WordPress instance with demo data and required plugins, using wp-env
7. Sitemaps for custom post and taxonomy types
8. Permanent redirect of `/sitemap` requests to `/sitemap.xml`, in the `next.config.mjs`

## Screenshots

After following the installation steps, you should have the example sitemap pages as shown in the screenshots below:

| | |
| :--------------------------------------------------------------------------: | :----------------------------------------------------------------------------------: |
| ![index](./screenshots/sitemap-index.png "Sitemap index")<br>Sitemap index | ![posts](./screenshots/sitemap-post.png "Posts")<br>Posts |
| ![categories](./screenshots/sitemap-category.png "Categories")<br>Categories | ![tags](./screenshots/sitemap-tag.png "Tags")<br>Tags |
| ![users](./screenshots/sitemap-user.png "Users")<br>Users | ![page](./screenshots/sitemap-page.png "Pages")<br>Pages |
| ![cpt](./screenshots/sitemap-cpt.png "Custom post type")<br>Custom post type | ![ctt](./screenshots/sitemap-ctt.png "Custom taxonomy type")<br>Custom taxonomy type |

## Project Structure

```
├── example-app # Next.js application root
│ ├── public
│ │ └── sitemap.xsl # XSLT style file for the sitemap
│ └── src
│ ├── components
│ ├── lib
│ │ ├── client.js # Apollo Client instance
│ │ └── generateSiteMap.js # Helper function that generates the XML content
│ └── pages
│ ├── sitemap # Base path for sitemap subpages
│ │ └── [...type] # Catch-all route for sitemap subpages
│ └── sitemap.xml.js # Index sitemap.xml page
├── hwpt-wpgraphql-sitemap # PHP files for the HWPT WPGraphQL Sitemap plugin
├── hwpt-wpgraphql-sitemap.zip # HWPT WPGraphQL Sitemap plugin to enable sitemap fields
├── .wp-env.json # wp-env configuration file
└── wp-env
├── db
│ └── database.sql # WordPress database including all demo data for the example
└── uploads.zip # WordPress content to be used by wp-env
```

## Important notes

- If you're intending to use this example with your own WordPress instance, make sure to uncheck the `Discourage search engines from indexing this site` checkbox under `Settings -> Reading` in the WordPress admin.
- If the XML sitemap feature in Yoast SEO is enabled, it will disable the native WordPress sitemap. To run this example, you must disable Yoast SEO's XML sitemap feature.

## Running the example with wp-env

### Prerequisites

- Node.js (v18+ recommended)
- [Docker](https://www.docker.com/) (if you plan on running the example see details below)

**Note** Please make sure you have all prerequisites installed as mentioned above and Docker running (`docker ps`)

### Setup Repository and Packages

- Clone the repo `git clone https://github.com/wpengine/hwptoolkit.git`
- Install packages `cd hwptoolkit && npm install`
- Setup a .env file under `examples/next/custom-sitemap-apollo/example-app` and add these values inside:

```
NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888
NEXT_PUBLIC_URL=http://localhost:3000
```

or run the command below:

```bash
echo "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888\\nNEXT_PUBLIC_URL=http://localhost:3000" > examples/next/custom-sitemap-apollo/example-app/.env
```

### Build and start the application

- `cd examples/next/custom-sitemap-apollo`
- Then run `npm run example:build` will build and start your application.
- This does the following:
- Unzips `wp-env/uploads.zip` to `wp-env/uploads` which is mapped to the wp-content/uploads directory for the Docker container.
- Starts up [wp-env](https://developer.wordpress.org/block-editor/getting-started/devenv/get-started-with-wp-env/)
- Imports the database from [wp-env/db/database.sql](wp-env/db/database.sql)
- Install Next.js dependencies for `example-app`
- Runs the Next.js dev script

Congratulations, WordPress should now be fully set up.

| Frontend | Admin |
| ------------------------------------------------ | ------------------------------------------------------------------ |
| [http://localhost:3000/](http://localhost:3000/) | [http://localhost:8888/wp-admin/](http://localhost:8888/wp-admin/) |

> **Note:** The login details for the admin is username "admin" and password "password"

### Command Reference

| Command | Description |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `example:build` | Prepares the environment by unzipping images, starting WordPress, importing the database, and starting the application. |
| `example:dev` | Runs the Next.js development server. |
| `example:dev:install` | Installs the required Next.js packages. |
| `example:start` | Starts WordPress and the Next.js development server. |
| `example:stop` | Stops the WordPress environment. |
| `example:prune` | Rebuilds and restarts the application by destroying and recreating the WordPress environment. |
| `wp:start` | Starts the WordPress environment. |
| `wp:stop` | Stops the WordPress environment. |
| `wp:destroy` | Completely removes the WordPress environment. |
| `wp:db:query` | Executes a database query within the WordPress environment. |
| `wp:db:export` | Exports the WordPress database to `wp-env/db/database.sql`. |
| `wp:db:import` | Imports the WordPress database from `wp-env/db/database.sql`. |
| `wp:images:unzip` | Extracts the WordPress uploads directory. |
| `wp:images:zip` | Compresses the WordPress uploads directory. |

> **Note** You can run `npm run wp-env` and use any other wp-env command. You can also see <https://www.npmjs.com/package/@wordpress/env> for more details on how to use or configure `wp-env`.

### Database access

If you need database access add the following to your wp-env `"phpmyadminPort": 11111,` (where port 11111 is not allocated).

You can check if a port is free by running `lsof -i :11111`
41 changes: 41 additions & 0 deletions examples/next/custom-sitemap-apollo/example-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname,
});

const eslintConfig = [...compat.extends("next/core-web-vitals")];

export default eslintConfig;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
15 changes: 15 additions & 0 deletions examples/next/custom-sitemap-apollo/example-app/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async redirects() {
return [
{
source: "/sitemap",
destination: "/sitemap.xml",
permanent: true,
},
];
},
};

export default nextConfig;
24 changes: 24 additions & 0 deletions examples/next/custom-sitemap-apollo/example-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "custom-sitemap-apollo-example-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@apollo/client": "^3.13.5",
"next": "15.2.4",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"eslint": "^9",
"eslint-config-next": "15.2.4",
"tailwindcss": "^4"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};

export default config;
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">

<xsl:output method="html" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
<html>
<head>
<title>XML Sitemap</title>
<style type="text/css">
body {
font-family: Arial, sans-serif;
padding: 40px;
max-width: 1600px;
margin: 0 auto;
}
table {
width: 100%;
margin-top: 40px;
}
th {
background-color: #dee2e6;
text-align: left;
padding: 10px;
}
tr:nth-child(odd) {
background-color: #f1f3f5;
}
td {
padding: 12px;
vertical-align: center;
word-break: break-all;
}
</style>
</head>
<body>
<h1>XML Sitemap</h1>
<p>Total URLs in this sitemap: <xsl:value-of select="count(sitemap:urlset/sitemap:url)"/></p>
<table>
<tr>
<th>URL</th>
<xsl:if test="//image:image">
<th>Image</th>
</xsl:if>
<xsl:if test="//sitemap:lastmod">
<th>Last Modified</th>
</xsl:if>
</tr>
<xsl:for-each select="sitemap:urlset/sitemap:url">
<tr>
<td>
<a href="{sitemap:loc}" >
<xsl:value-of select="sitemap:loc"/>
</a>
</td>

<xsl:if test="//image:image">
<td>
<xsl:for-each select="image:image">
<a href="{image:loc}" target="_blank">
<xsl:value-of select="image:loc"/>
</a>
</xsl:for-each>
</td>
</xsl:if>

<xsl:if test="//sitemap:lastmod">
<td>
<xsl:if test="sitemap:lastmod">
<xsl:value-of select="substring(sitemap:lastmod, 1)"/>
</xsl:if>
</td>
</xsl:if>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { BlogPostItem } from "@/components/BlogPostItem";
import Head from "next/head";

export default function Archive({ posts, type, title }) {
const pageTitle = type + ": " + title;

return (
<>
<Head>
<title>{pageTitle}</title>
</Head>

<h1 className='container max-w-4xl py-6 mx-auto mb-4 text-2xl font-bold'>{pageTitle}</h1>

{posts?.map((item) => {
const post = item.node;

return <BlogPostItem key={post.id} post={post} />;
})}
</>
);
}
Loading