-
Notifications
You must be signed in to change notification settings - Fork 1
docs: Next.js WP Theme rendered blocks #115
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
Open
whoami-pwd
wants to merge
19
commits into
main
Choose a base branch
from
example-wp-theme-rendered-blocks
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,979
−1
Open
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
a496e09
Adds WP plugin example for the stylesheet exposure.
whoami-pwd 4d3c0a5
Provides CLI command.
whoami-pwd 9951d2c
Updates readme.
whoami-pwd c6d504e
Reverts pnpm-lock.yaml changes.
whoami-pwd e62df79
Updates JS example.
whoami-pwd 671d3ba
Moves the plugin to the example folder.
whoami-pwd ac1d7b4
Merge branch 'main' into example-wp-theme-rendered-blocks
whoami-pwd 72324e6
Fixes lock typo.
whoami-pwd 7b73aa3
Moves plugin to the separate example folder.
whoami-pwd add904e
Restores original versions of the example.
whoami-pwd b40ab65
Provides example files.
whoami-pwd 0760b8e
Resets files
whoami-pwd 7b62e79
Provides the wp-env configuration.
whoami-pwd 644ceba
Provides the wp-env configuration.
whoami-pwd 71abfa9
Updates the README.md.
whoami-pwd c07baf2
Apply suggestions from code review
ahuseyn e54bb4d
fix: pnpm to npm
ahuseyn 3310fc5
fix: fetchWpGlobalStyles cjs to esm
ahuseyn e2bc7ee
docs: minor fixes
ahuseyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
{ | ||
"phpVersion": "7.4", | ||
"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", | ||
"./wp-env/plugins/hwp-global-stylesheet" | ||
], | ||
"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 rewrite structure '/%postname%/' && wp-env run cli -- wp rewrite flush" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
# Example: WordPress Global Styles in Next.js | ||
|
||
This example demonstrates how to **fetch and apply WordPress Global Styles** in a Next.js project using the `globalStylesheet` GraphQL field. These styles reflect your active theme’s typography, spacing, colors, and layout rules — ensuring that your frontend matches the WordPress editor and theme design. | ||
|
||
This pattern is especially helpful for users migrating from **Faust.js**, where similar global styles were automatically applied using utilities like `getGlobalStyles`. | ||
|
||
--- | ||
|
||
## How it works | ||
|
||
- A script (`scripts/fetchWpGlobalStyles.mjs`) queries your WordPress site's GraphQL API for global styles. | ||
- The styles are saved to `styles/hwp-global-styles.css`. | ||
- The file is imported directly in your app and bundled at build time. | ||
|
||
This ensures that all block-rendered content in your app inherits the same styling as it would inside the WordPress editor. | ||
|
||
--- | ||
|
||
## Example usage | ||
|
||
In `scripts/fetchWpGlobalStyles.mjs`, you define the fetch: | ||
|
||
```js | ||
fetchWpGlobalStyles( | ||
"https://your-wp-site.com/graphql", // WordPress GraphQL endpoint | ||
"styles/hwp-global-styles.css", // Output path | ||
["variables", "presets", "styles", "base-layout-styles"] // Style types to include | ||
); | ||
``` | ||
|
||
In your `pages/_app.js`, you include the styles: | ||
|
||
```javascript | ||
import "@wordpress/base-styles"; // WordPress foundational styles | ||
import "@/styles/hwp-global-styles.css"; // Theme styles fetched from WP | ||
import "@/styles/globals.css"; // Optional custom app styles | ||
``` | ||
|
||
## Project structure | ||
|
||
``` | ||
/ | ||
├── hwp-global-stylesheet/* # WordPress Plugin. | ||
├── pages/ | ||
│ ├── _app.js # Includes global styles. | ||
│ └── index.js # Basic page. | ||
├── styles/ | ||
│ ├── hwp-global-styles.css # Output of the fetch script. | ||
│ └── globals.css # Your optional global app styles. | ||
├── package.json # Project dependencies and scripts. | ||
``` | ||
|
||
## Installation and Setup | ||
|
||
### Prerequisites | ||
|
||
1. Node.js 18.18 or later | ||
2. npm or another package manager | ||
ahuseyn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
3. [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`) | ||
|
||
### Clone the repository | ||
|
||
```bash | ||
git clone https://github.com/wpengine/hwptoolkit.git | ||
``` | ||
|
||
### Install dependencies | ||
|
||
```bash | ||
cd hwptoolkit && npm install | ||
``` | ||
|
||
### Build and start the application | ||
|
||
- `cd examples/next/wp-theme-rendered-blocks` | ||
- Then run `npm run example:build` will build and start your application. | ||
- This does the following: | ||
- 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" |
41 changes: 41 additions & 0 deletions
41
examples/next/wp-theme-rendered-blocks/example-app/.gitignore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
lts/* |
20 changes: 20 additions & 0 deletions
20
examples/next/wp-theme-rendered-blocks/example-app/eslint.config.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { FlatCompat } from "@eslint/eslintrc"; | ||
import js from "@eslint/js"; | ||
import { dirname } from "path"; | ||
import { fileURLToPath } from "url"; | ||
|
||
const __filename = fileURLToPath(import.meta.url); | ||
const __dirname = dirname(__filename); | ||
|
||
const compat = new FlatCompat({ | ||
baseDirectory: __dirname, | ||
recommendedConfig: js.configs.recommended, | ||
}); | ||
|
||
const eslintConfig = [ | ||
...compat.config({ | ||
extends: ["eslint:recommended", "next/core-web-vitals"], | ||
}), | ||
]; | ||
|
||
export default eslintConfig; |
7 changes: 7 additions & 0 deletions
7
examples/next/wp-theme-rendered-blocks/example-app/jsconfig.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"compilerOptions": { | ||
"paths": { | ||
"@/*": ["./src/*"] | ||
} | ||
} | ||
} |
6 changes: 6 additions & 0 deletions
6
examples/next/wp-theme-rendered-blocks/example-app/next.config.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
/** @type {import('next').NextConfig} */ | ||
const nextConfig = { | ||
reactStrictMode: true, | ||
}; | ||
|
||
export default nextConfig; |
24 changes: 24 additions & 0 deletions
24
examples/next/wp-theme-rendered-blocks/example-app/package.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
{ | ||
"name": "wp-theme-styles-nextjs", | ||
"version": "0.1.0", | ||
"private": true, | ||
"scripts": { | ||
"dev": "next dev", | ||
"build": "next build", | ||
"start": "next start", | ||
"lint": "next lint", | ||
"prettier": "prettier --write .", | ||
"styles:fetch": "node scripts/fetchWpGlobalStyles.mjs" | ||
}, | ||
"dependencies": { | ||
"@wordpress/base-styles": "^5.21.0", | ||
"next": "15.2.4", | ||
"prettier": "^3.5.3", | ||
"react": "^19.0.0", | ||
"react-dom": "^19.0.0" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^9", | ||
"eslint-config-next": "15.2.3" | ||
} | ||
} |
49 changes: 49 additions & 0 deletions
49
examples/next/wp-theme-rendered-blocks/example-app/scripts/fetchWpGlobalStyles.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import fs from "fs"; | ||
import path from "path"; | ||
|
||
async function fetchWpGlobalStyles( | ||
endpoint, | ||
outputPath = "src/styles/hwp-global-styles.css", | ||
types = ["variables", "presets", "styles", "base-layout-styles"] | ||
) { | ||
const typeEnums = types.map((type) => type.toUpperCase().replace(/-/g, "_")); | ||
|
||
const query = ` | ||
query { | ||
globalStylesheet(types: [${typeEnums.join(", ")}]) | ||
} | ||
`; | ||
|
||
try { | ||
const response = await fetch(endpoint, { | ||
method: "POST", | ||
headers: { "Content-Type": "application/json" }, | ||
body: JSON.stringify({ query }), | ||
}); | ||
|
||
const json = await response.json(); | ||
|
||
if (!json.data || !json.data.globalStylesheet) { | ||
throw new Error("No stylesheet data returned from the API."); | ||
} | ||
|
||
let css = json.data.globalStylesheet; | ||
|
||
// Optional minification for production use | ||
css = css | ||
.replace(/\/\*[\s\S]*?\*\//g, "") | ||
.replace(/\s+/g, " ") | ||
.replace(/\s*([{}:;,])\s*/g, "$1") | ||
.trim(); | ||
|
||
const absoluteOutputPath = path.resolve(process.cwd(), outputPath); | ||
fs.mkdirSync(path.dirname(absoluteOutputPath), { recursive: true }); | ||
fs.writeFileSync(absoluteOutputPath, css); | ||
|
||
console.log(`Global styles saved to: ${absoluteOutputPath}`); | ||
} catch (error) { | ||
console.error("Error fetching global styles:", error.message); | ||
} | ||
} | ||
|
||
fetchWpGlobalStyles("http://localhost:8888/graphql"); |
7 changes: 7 additions & 0 deletions
7
examples/next/wp-theme-rendered-blocks/example-app/src/pages/_app.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import '@wordpress/base-styles'; // WordPress foundational styles. | ||
import '@/styles/hwp-global-styles.css'; // The fetched global styles from WP (generated by your fetch script). | ||
import "@/styles/globals.css"; // Optional custom global styles. | ||
|
||
export default function App({ Component, pageProps }) { | ||
return <Component {...pageProps} />; | ||
} |
13 changes: 13 additions & 0 deletions
13
examples/next/wp-theme-rendered-blocks/example-app/src/pages/_document.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { Html, Head, Main, NextScript } from "next/document"; | ||
|
||
export default function Document() { | ||
return ( | ||
<Html lang="en"> | ||
<Head /> | ||
<body className="antialiased"> | ||
<Main /> | ||
<NextScript /> | ||
</body> | ||
</Html> | ||
); | ||
} |
20 changes: 20 additions & 0 deletions
20
examples/next/wp-theme-rendered-blocks/example-app/src/pages/index.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import Head from "next/head"; | ||
|
||
export default function Home() { | ||
return ( | ||
<> | ||
<Head> | ||
<title>WordPress Theme Styles Example</title> | ||
</Head> | ||
<main> | ||
<h1>WordPress Global Styles in Next.js</h1> | ||
<p> | ||
This example shows how to fetch and apply global styles from a WordPress site using WPGraphQL. The theme styles you're seeing here were fetched from the WP instance and applied globally via CSS. | ||
</p> | ||
<p> | ||
You can now render blocks in another part of your app and they will inherit the theme styling from your WordPress site. | ||
</p> | ||
</main> | ||
</> | ||
); | ||
} |
9 changes: 9 additions & 0 deletions
9
examples/next/wp-theme-rendered-blocks/example-app/src/styles/globals.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
.wp-element-caption { | ||
font-size: 0.875rem; | ||
line-height: 1.4; | ||
} | ||
|
||
.is-layout-flex { | ||
display: flex; | ||
gap: 1.2rem; | ||
} |
1 change: 1 addition & 0 deletions
1
examples/next/wp-theme-rendered-blocks/example-app/src/styles/hwp-global-styles.css
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/** Output from the script. **/ |
Binary file not shown.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using the latest versions is good; we might want to consider pinning to a specific version of each plugin to mitigate examples breaking on future updates.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@josephfusco That's a good point.
I created this task here as we also need to consider a few other things - #148