Skip to content

Commit 1bd01ec

Browse files
authored
Merge pull request #122 from wpengine/feat-client-example-multisite
feat: Client Multisite example
2 parents 6b33bdb + 22faf12 commit 1bd01ec

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

72 files changed

+8773
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ test-results/
1414
.wp-env
1515
.wp-env.override.json
1616
uploads/
17+
debug.log
1718

1819
# Environment
1920
.env

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ This directory contains examples demonstrating how to use various features of th
44

55
- **next-pages-apollo-authentication**: An example project showcasing authentication with Next.js, Apollo Client, and Headless WordPress.
66
- **next/client-app-router-fetch-data**: An example WordPress application using Next.js App Router and the fetch API to fetch data from WordPress using WPGraphQL
7+
- **next/client-multisite-app-router-fetch-data**: An example WordPress multisite application using Next.js App Router and the fetch API to fetch data from WordPress using WPGraphQL
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"phpVersion": "7.4",
3+
"port": 8888,
4+
"plugins": [
5+
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
6+
"https://github.com/wp-graphql/wpgraphql-ide/releases/latest/download/wpgraphql-ide.zip",
7+
"https://github.com/AdvancedCustomFields/acf/releases/download/6.3.12/advanced-custom-fields-6.3.12.zip",
8+
"https://github.com/wp-graphql/wpgraphql-acf/releases/latest/download/wpgraphql-acf.zip",
9+
"https://github.com/wpengine/wp-graphql-content-blocks/releases/latest/download/wp-graphql-content-blocks.zip"
10+
],
11+
"config": {
12+
"WP_DEBUG": true,
13+
"SCRIPT_DEBUG": false,
14+
"GRAPHQL_DEBUG": true,
15+
"WP_DEBUG_LOG": true,
16+
"WP_DEBUG_DISPLAY": false,
17+
"SAVEQUERIES": false
18+
},
19+
"mappings": {
20+
"db": "./wp-env/db",
21+
"wp-content/debug.log": "./wp-env/log/",
22+
"wp-content/uploads": "./wp-env/uploads",
23+
".htaccess": "./wp-env/setup/.htaccess"
24+
},
25+
"lifecycleScripts": {
26+
"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"
27+
}
28+
}
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
# Example: Multisite Next.js App Router using the Fetch API
2+
3+
# Table of Contents
4+
- [Overview](#overview)
5+
- [Prerequisites](#prerequisites)
6+
- [Project Structure](#project-structure)
7+
- [Features](#features)
8+
- [Screenshots](#screenshots)
9+
- [Running the Example with wp-env](#running-the-example-with-wp-env)
10+
- [Prerequisites](#prerequisites-1)
11+
- [Setup Repository and Packages](#setup-repository-and-packages)
12+
- [Build and Start the Application](#build-and-start-the-application)
13+
- [Command Reference](#command-reference)
14+
- [Database Access](#database-access)
15+
- [Adding More Sites to the Multisite Examples](#adding-more-sites-to-the-multisite-examples)
16+
17+
18+
# Overview
19+
20+
An example mulitsite headless WordPress application using Next.js App Router and the fetch API to fetch data from WordPress using WPGraphQL. It showcases different data fetching strategies, state management techniques, and modern web development patterns in a real-world application context. This also contains a full example using wp-env and sample data.
21+
22+
## Prerequisites
23+
24+
- Node.js (v18+ recommended)
25+
- [pnpm](https://pnpm.io/)
26+
- [Docker](https://www.docker.com/) (if you plan on running the example see details below)
27+
28+
29+
## Project Structure
30+
31+
```
32+
/
33+
├── example-app/ # Next.js App Headless Example Application
34+
│ ├── app/ # Application-specific pages and routes
35+
│ ├── components/ # Reusable UI components
36+
│ ├── lib/ # Utility functions and libraries and WP GraphQL Fragments
37+
|
38+
├── wp-env/ # WordPress local environment setup
39+
│ ├── wp-env.json
40+
│ ├── db/ # Example database export to be imported for the example setup
41+
│ ├── setup/ # .htaccess file to fix a CORS issue
42+
| |── log/ # Log file for wp-content/debug.log
43+
| |-- screenshots/ # Example screenshots for this README
44+
│ ├── uploads.zip # Zipped wp-content/uploads directory for the example application
45+
│ ├── uploads/ # Unzipped wp-content/uploads directory when the example application is run.
46+
├── package.json # Scripts for running the example application
47+
```
48+
49+
## Features
50+
51+
- **Covers various rendering patterns of Next.js**
52+
53+
- Server-Side Rendering (SSR) for dynamic pages
54+
- Static Site Generation (SSG) for static pages
55+
- Client-Side data fetching (CSR) for blog settings
56+
- Hybrid data fetching, combining SSR and CSR
57+
58+
- **Multisite Features**
59+
60+
- Dynamic site management in next.config.mjs
61+
- Fetch data based off site key defined in next.config.mjs
62+
- Homepage dynamically fetches and displays data from multiple WordPress sites in the multisite network.
63+
64+
- **Catch-All Template**
65+
66+
- The catch-all template fetches data from all WordPress sites in the multisite network.
67+
- It loops through each site until it finds the relevant data to display.
68+
- Can be extended on a per site basis for querying different fragments
69+
70+
- **Blog features**
71+
72+
- Listing posts with pagination
73+
- Fetching posts and pages using nodeByUri of WPGraphQL
74+
- Fetching static pages at build time
75+
- Commenting posts
76+
- Header with dynamic blog title
77+
- Featured image
78+
- Includes category and tag blog post listings
79+
80+
- **Other Template Features**
81+
- Page template
82+
- CPT template with listings for a CPT events (can be adapted for other CPT)
83+
- Single CPT page with ACF custom meta fields
84+
85+
## Screenshots
86+
87+
![Home](wp-env/screenshots/Home.png)
88+
![Blog Listing](wp-env/screenshots/Blog_listing.png)
89+
![Blog Listing Pagination](wp-env/screenshots/Blog_listing_pagination.png)
90+
![Single Blog Page](wp-env/screenshots/Single_blog.png)
91+
![Comments](wp-env/screenshots/Comments.png)
92+
![Comment Form](wp-env/screenshots/Comment_form.png)
93+
![Catch All](wp-env/screenshots/Catch_all.png)
94+
![Catch All second site](wp-env/screenshots/Catch_all_second_site.png)
95+
![CPT Second site](wp-env/screenshots/cpt.png)
96+
97+
# Running the example with wp-env
98+
99+
## Prerequisites
100+
101+
**Note** Please make sure you have all prerequisites installed as mentioned above and Docker running (`docker ps`)
102+
103+
## Setup Repository and Packages
104+
105+
- Clone the repo `git clone https://github.com/wpengine/hwptoolkit.git`
106+
- Install packages `cd hwptoolkit && pnpm install`
107+
- Setup a .env file under `examples/next/client-multisite-app-router-fetch-data/example-app` with
108+
109+
```
110+
NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888
111+
NEXT_PUBLIC_MOVIE_WORDPRESS_URL=http://localhost:8888/movies
112+
```
113+
114+
e.g.
115+
116+
```bash
117+
echo "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888" > examples/next/client-multisite-app-router-fetch-data/example-app/.env
118+
echo "NEXT_PUBLIC_MOVIE_WORDPRESS_URL=http://localhost:8888/movies" >> examples/next/client-multisite-app-router-fetch-data/example-app/.env
119+
```
120+
121+
> [!IMPORTANT]
122+
> The site configuration is based off values set in [example-app/next.config.mjs](example-app/next.config.mjs)
123+
> If you want to add more sites please feel free to add more sites to your .env file and update the configuration in the next.config.mjs
124+
125+
126+
## Build and start the application
127+
128+
- `cd examples/next/client-multisite-app-router-fetch-data`
129+
- Then run `pnpm example:build` will build and start your application.)
130+
- This does the following:
131+
- Unzips `wp-env/uploads.zip` to `wp-env/uploads` which is mapped to the wp-content/uploads directory for the Docker container.
132+
- Starts up [wp-env](https://developer.wordpress.org/block-editor/getting-started/devenv/get-started-with-wp-env/)
133+
- Imports the database from [wp-env/db/database.sql](wp-env/db/database.sql)
134+
- Sets the mulitisite wp-config.php variables
135+
- Install Next.js dependencies for `example-app`
136+
- Runs the Next.js dev script
137+
138+
Congratulations, WordPress should now be fully set up.
139+
140+
| Frontend | Admin |
141+
|----------|------------------------------|
142+
| [http://localhost:3000/](http://localhost:3000/) | [http://localhost:8888/wp-admin/](http://localhost:8888/wp-admin/) |
143+
144+
The login details for the admin is username "admin" and password "password"
145+
146+
147+
> [!IMPORTANT]
148+
There are issues with setting variables for multisite in .wp-env.json before converting the site to multisite. For this reason we set the variables after the sample database (which is multisite) is imported.
149+
**You also need to update the port in wp:multisite:set:variables if you ever change 8888**
150+
151+
## Command Reference
152+
153+
| Command | Description |
154+
|-----------------------------|-----------------------------------------------------------------------------|
155+
| `example:build` | Prepares the environment by unzipping images, starting WordPress, importing the database, and starting the application. |
156+
| `example:dev` | Runs the Next.js development server. |
157+
| `example:dev:install` | Installs the required Next.js packages. |
158+
| `example:start` | Starts WordPress, sets the multisite variables, and starts the Next.js development server. |
159+
| `example:stop` | Stops the WordPress environment. |
160+
| `example:prune` | Rebuilds and restarts the application by destroying and recreating the WordPress environment. |
161+
| `wp:start` | Starts the WordPress environment. |
162+
| `wp:stop` | Stops the WordPress environment. |
163+
| `wp:multisite:set:variables`| Sets the variables for multisite in `wp-config.php`. |
164+
| `wp:destroy` | Completely removes the WordPress environment. |
165+
| `wp:db:query` | Executes a database query within the WordPress environment. |
166+
| `wp:db:export` | Exports the WordPress database to `wp-env/db/database.sql`. |
167+
| `wp:db:import` | Imports the WordPress database from `wp-env/db/database.sql`. |
168+
| `wp:images:unzip` | Extracts the WordPress uploads directory. |
169+
| `wp:images:zip` | Compresses the WordPress uploads directory. |
170+
171+
172+
>**Note** You can run `pnpm 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`.
173+
174+
### Database access
175+
176+
If you need database access add the following to your wp-env `"phpmyadminPort": 11111,` (where port 11111 is not allocated).
177+
178+
You can check if a port is free by running `lsof -i :11111`
179+
180+
### Adding more sites to the multisite examples
181+
182+
If you want to add more sites you need to do the followint
183+
184+
1. Add the variable to your .env next.js setup e.g. `NEXT_PUBLIC_SPORT_WORDPRESS_URL=http://localhost:8888/sport`
185+
2. Update your next.config.mjs with a site key and this value e.g.
186+
```js
187+
WORDPRESS_SITES: JSON.stringify({
188+
main: process.env.NEXT_PUBLIC_WORDPRESS_URL + "/graphql",
189+
movie_site: process.env.NEXT_PUBLIC_MOVIE_WORDPRESS_URL + "/graphql",
190+
sport_site: process.env.NEXT_PUBLIC_SPORT_WORDPRESS_URL + "/graphql",
191+
}),
192+
```
193+
194+
You then use the site key e.g. `sport_site` when fetching data with a template or the `fetchGraphQL` function
195+
196+
e.g.
197+
198+
```
199+
# example-app/src/app/sport-news/page.js
200+
import { SportsListingsQuery } from "@/lib/queries/SportsListingsQuery";
201+
import { CustomPostTypeTemplate } from "@/components/cpt/CustomPostTypeTemplate";
202+
203+
export default async function SportsListingsPage(params) {
204+
return CustomPostTypeTemplate(SportsListingsQuery, {
205+
params: params,
206+
customPostType: "sport", # Update CPT
207+
siteKey: "sport_site", # This is your site key
208+
title: "Sport News",
209+
cacheExpiry: 3600,
210+
});
211+
}
212+
213+
```
214+
215+
**Note**
216+
217+
1. You need to add the query
218+
2. You also need to update the Custom Post Type Template to include your listings template
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.*
7+
.yarn/*
8+
!.yarn/patches
9+
!.yarn/plugins
10+
!.yarn/releases
11+
!.yarn/versions
12+
13+
# testing
14+
/coverage
15+
16+
# next.js
17+
/.next/
18+
/out/
19+
20+
# production
21+
/build
22+
23+
# misc
24+
.DS_Store
25+
*.pem
26+
27+
# debug
28+
npm-debug.log*
29+
yarn-debug.log*
30+
yarn-error.log*
31+
.pnpm-debug.log*
32+
33+
# env files (can opt-in for committing if needed)
34+
.env*
35+
36+
# vercel
37+
.vercel
38+
39+
# typescript
40+
*.tsbuildinfo
41+
next-env.d.ts
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { dirname } from "path";
2+
import { fileURLToPath } from "url";
3+
import { FlatCompat } from "@eslint/eslintrc";
4+
5+
const __filename = fileURLToPath(import.meta.url);
6+
const __dirname = dirname(__filename);
7+
8+
const compat = new FlatCompat({
9+
baseDirectory: __dirname,
10+
});
11+
12+
const eslintConfig = [...compat.extends("next/core-web-vitals")];
13+
14+
export default eslintConfig;
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"compilerOptions": {
3+
"paths": {
4+
"@/*": ["./src/*"]
5+
}
6+
}
7+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/** @type {import('next').NextConfig} */
2+
const nextConfig = {
3+
reactStrictMode: true,
4+
images: {
5+
// Allow images from localhost.
6+
// Please change this to your domain if you are using a different domain.
7+
domains: ["localhost"],
8+
},
9+
env: {
10+
// A list of sites to be used in the app. See src/lib/client.js for more info.
11+
WORDPRESS_SITES: JSON.stringify({
12+
main: process.env.NEXT_PUBLIC_WORDPRESS_URL + "/graphql",
13+
movie_site: process.env.NEXT_PUBLIC_MOVIE_WORDPRESS_URL + "/graphql",
14+
}),
15+
},
16+
// Note: env variables are set in next.config.js only accept string values so used publicRuntimeConfig instead
17+
publicRuntimeConfig: {
18+
// Controls posts per page for blog, category and tag pages
19+
wordPressDisplaySettings: {
20+
postsPerPage: 5,
21+
},
22+
},
23+
};
24+
25+
export default nextConfig;

0 commit comments

Comments
 (0)