Skip to content

feat: Client Multisite example #122

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 25 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
8bc623b
Initial wp-env scaffold. Not tested yet.
colinmurphy Mar 26, 2025
c0b04a3
Setup next.js vanilla install. Fixed wp env setup for multisite. You …
colinmurphy Mar 26, 2025
2a49fff
Updated README
colinmurphy Mar 27, 2025
a44d72d
Merge branch 'main' into feat-client-example-multisite
colinmurphy Mar 27, 2025
4ab1efe
Setup layout for app. Fixed metadata for previous client example.
colinmurphy Mar 27, 2025
a00b77d
Added blog listing template. Setup util client. Add multisite configu…
colinmurphy Mar 28, 2025
babba11
Added listing for the second site. Fixed a few responsive issues
colinmurphy Mar 28, 2025
71470cb
Added category and tag listing pages. Refactor heading and a few smal…
colinmurphy Mar 31, 2025
8a93fb3
Reverted change.
colinmurphy Mar 31, 2025
e6d6bc4
Refactor of blog/cpt listing templates so they can be re-used elsewhere
colinmurphy Mar 31, 2025
f2e9dee
Added homepage. Refactored listing templates to include additional ar…
colinmurphy Mar 31, 2025
3a75805
Refactored button component.
colinmurphy Mar 31, 2025
646359b
Added catch all template. Added single page and post templates. Added…
colinmurphy Mar 31, 2025
16bc8c8
Updated sample database.
colinmurphy Mar 31, 2025
5c8b987
Added single CPT for Moveis for catch all. Reverted other changes.
colinmurphy Apr 1, 2025
8c5cb25
Exported sample database.
colinmurphy Apr 1, 2025
07214db
Prettify templates
colinmurphy Apr 1, 2025
487a6d3
Merge branch 'main' into feat-client-example-multisite
colinmurphy Apr 2, 2025
0561a86
Merge branch 'main' into feat-client-example-multisite
colinmurphy Apr 4, 2025
e104a80
Updated README. Added screenshots
colinmurphy Apr 4, 2025
cd13c8c
Fix for README
colinmurphy Apr 4, 2025
f7913c3
Updated README with info about adding more sites
colinmurphy Apr 4, 2025
9345bd0
Added LLMs.txt
colinmurphy Apr 4, 2025
f270750
Update examples/next/client-multisite-app-router-fetch-data/README.md
colinmurphy Apr 4, 2025
22faf12
Update examples/next/client-multisite-app-router-fetch-data/README.md
colinmurphy Apr 4, 2025
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ test-results/
.wp-env
.wp-env.override.json
uploads/
debug.log

# Environment
.env
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ This directory contains examples demonstrating how to use various features of th

- **next-pages-apollo-authentication**: An example project showcasing authentication with Next.js, Apollo Client, and Headless WordPress.
- **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
- **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
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"phpVersion": "7.4",
"port": 8888,
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
"https://github.com/wp-graphql/wpgraphql-ide/releases/latest/download/wpgraphql-ide.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/wp-graphql-content-blocks/releases/latest/download/wp-graphql-content-blocks.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/debug.log": "./wp-env/log/",
"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"
}
}
218 changes: 218 additions & 0 deletions examples/next/client-multisite-app-router-fetch-data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
# Example: Multisite Next.js App Router using the Fetch API

# Table of Contents
- [Overview](#overview)
- [Prerequisites](#prerequisites)
- [Project Structure](#project-structure)
- [Features](#features)
- [Screenshots](#screenshots)
- [Running the Example with wp-env](#running-the-example-with-wp-env)
- [Prerequisites](#prerequisites-1)
- [Setup Repository and Packages](#setup-repository-and-packages)
- [Build and Start the Application](#build-and-start-the-application)
- [Command Reference](#command-reference)
- [Database Access](#database-access)
- [Adding More Sites to the Multisite Examples](#adding-more-sites-to-the-multisite-examples)


# Overview

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.

## Prerequisites

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


## Project Structure

```
/
├── example-app/ # Next.js App Headless Example Application
│ ├── app/ # Application-specific pages and routes
│ ├── components/ # Reusable UI components
│ ├── lib/ # Utility functions and libraries and WP GraphQL Fragments
|
├── wp-env/ # WordPress local environment setup
│ ├── wp-env.json
│ ├── db/ # Example database export to be imported for the example setup
│ ├── setup/ # .htaccess file to fix a CORS issue
| |── log/ # Log file for wp-content/debug.log
| |-- screenshots/ # Example screenshots for this README
│ ├── uploads.zip # Zipped wp-content/uploads directory for the example application
│ ├── uploads/ # Unzipped wp-content/uploads directory when the example application is run.
├── package.json # Scripts for running the example application
```

## Features

- **Covers various rendering patterns of Next.js**

- Server-Side Rendering (SSR) for dynamic pages
- Static Site Generation (SSG) for static pages
- Client-Side data fetching (CSR) for blog settings
- Hybrid data fetching, combining SSR and CSR

- **Multisite Features**

- Dynamic site management in next.config.mjs
- Fetch data based off site key defined in next.config.mjs
- Homepage dynamically fetches and displays data from multiple WordPress sites in the multisite network.

- **Catch-All Template**

- The catch-all template fetches data from all WordPress sites in the multisite network.
- It loops through each site until it finds the relevant data to display.
- Can be extended on a per site basis for querying different fragments

- **Blog features**

- Listing posts with pagination
- Fetching posts and pages using nodeByUri of WPGraphQL
- Fetching static pages at build time
- Commenting posts
- Header with dynamic blog title
- Featured image
- Includes category and tag blog post listings

- **Other Template Features**
- Page template
- CPT template with listings for a CPT events (can be adapted for other CPT)
- Single CPT page with ACF custom meta fields

## Screenshots

![Home](wp-env/screenshots/Home.png)
![Blog Listing](wp-env/screenshots/Blog_listing.png)
![Blog Listing Pagination](wp-env/screenshots/Blog_listing_pagination.png)
![Single Blog Page](wp-env/screenshots/Single_blog.png)
![Comments](wp-env/screenshots/Comments.png)
![Comment Form](wp-env/screenshots/Comment_form.png)
![Catch All](wp-env/screenshots/Catch_all.png)
![Catch All second site](wp-env/screenshots/Catch_all_second_site.png)
![CPT Second site](wp-env/screenshots/cpt.png)

# Running the example with wp-env

## Prerequisites

**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 && pnpm install`
- Setup a .env file under `examples/next/client-multisite-app-router-fetch-data/example-app` with

```
NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888
NEXT_PUBLIC_MOVIE_WORDPRESS_URL=http://localhost:8888/movies
```

e.g.

```bash
echo "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8888" > examples/next/client-multisite-app-router-fetch-data/example-app/.env
echo "NEXT_PUBLIC_MOVIE_WORDPRESS_URL=http://localhost:8888/movies" >> examples/next/client-multisite-app-router-fetch-data/example-app/.env
```

> [!IMPORTANT]
> The site configuration is based off values set in [example-app/next.config.mjs](example-app/next.config.mjs)
> 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


## Build and start the application

- `cd examples/next/client-multisite-app-router-fetch-data`
- Then run `pnpm 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)
- Sets the mulitisite wp-config.php variables
- 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/) |

The login details for the admin is username "admin" and password "password"


> [!IMPORTANT]
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.
**You also need to update the port in wp:multisite:set:variables if you ever change 8888**

## 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, sets the multisite variables, and starts 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:multisite:set:variables`| Sets the variables for multisite in `wp-config.php`. |
| `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 `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`.

### 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`

### Adding more sites to the multisite examples

If you want to add more sites you need to do the followint

1. Add the variable to your .env next.js setup e.g. `NEXT_PUBLIC_SPORT_WORDPRESS_URL=http://localhost:8888/sport`
2. Update your next.config.mjs with a site key and this value e.g.
```js
WORDPRESS_SITES: JSON.stringify({
main: process.env.NEXT_PUBLIC_WORDPRESS_URL + "/graphql",
movie_site: process.env.NEXT_PUBLIC_MOVIE_WORDPRESS_URL + "/graphql",
sport_site: process.env.NEXT_PUBLIC_SPORT_WORDPRESS_URL + "/graphql",
}),
```

You then use the site key e.g. `sport_site` when fetching data with a template or the `fetchGraphQL` function

e.g.

```
# example-app/src/app/sport-news/page.js
import { SportsListingsQuery } from "@/lib/queries/SportsListingsQuery";
import { CustomPostTypeTemplate } from "@/components/cpt/CustomPostTypeTemplate";

export default async function SportsListingsPage(params) {
return CustomPostTypeTemplate(SportsListingsQuery, {
params: params,
customPostType: "sport", # Update CPT
siteKey: "sport_site", # This is your site key
title: "Sport News",
cacheExpiry: 3600,
});
}

```

**Note**

1. You need to add the query
2. You also need to update the Custom Post Type Template to include your listings template
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/*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
// Allow images from localhost.
// Please change this to your domain if you are using a different domain.
domains: ["localhost"],
},
env: {
// A list of sites to be used in the app. See src/lib/client.js for more info.
WORDPRESS_SITES: JSON.stringify({
main: process.env.NEXT_PUBLIC_WORDPRESS_URL + "/graphql",
movie_site: process.env.NEXT_PUBLIC_MOVIE_WORDPRESS_URL + "/graphql",
}),
},
// Note: env variables are set in next.config.js only accept string values so used publicRuntimeConfig instead
publicRuntimeConfig: {
// Controls posts per page for blog, category and tag pages
wordPressDisplaySettings: {
postsPerPage: 5,
},
},
};

export default nextConfig;
Loading