Skip to content

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

Merged
merged 19 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from 12 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
41 changes: 41 additions & 0 deletions examples/next/wp-theme-rendered-blocks/.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
1 change: 1 addition & 0 deletions examples/next/wp-theme-rendered-blocks/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lts/*
81 changes: 81 additions & 0 deletions examples/next/wp-theme-rendered-blocks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# 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.js`) 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.js`, 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
3. WPGraphql
4. HWP Global Stylesheet Plugin

### Clone the repository

```bash
git clone https://github.com/wpengine/hwptoolkit.git
cd examples/next/render-blocks-pages-router
```

### Install dependencies

```bash
npm install
```

### Start the development server

```bash
npm run dev
```

http://localhost:3000/ should render the blocks as shown below.
20 changes: 20 additions & 0 deletions examples/next/wp-theme-rendered-blocks/eslint.config.mjs
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;
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php
/**
* Plugin Name: HWP Global Stylesheet
* Description: Exposes WordPress global stylesheets through WPGraphQL
* Version: 1.0.0
* Author: WP Engine
* Text Domain: hwp-global-stylesheet
* Domain Path: /languages
*
* @package WPGlobalStylesheet
*/

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}

/**
* Class WP_Global_Stylesheet
*/
class WP_Global_Stylesheet {

/**
* Instance of this class.
*
* @var WP_Global_Stylesheet
*/
private static $instance = null;

/**
* Get an instance of this class.
*
* @return WP_Global_Stylesheet
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}

/**
* Initialize the plugin.
*/
private function __construct() {
// Check if WPGraphQL is active
if ( class_exists( 'WPGraphQL' ) ) {
add_action( 'graphql_register_types', [ $this, 'register_global_stylesheet_field' ] );
return;
}

// Add admin notice if WPGraphQL is not active
add_action( 'admin_notices', [ $this, 'wpgraphql_missing_notice' ] );
}

/**
* Admin notice for missing WPGraphQL dependency.
*/
public function wpgraphql_missing_notice() {
if ( current_user_can( 'activate_plugins' ) ) {
?>
<div class="notice notice-error">
<p><?php esc_html_e( 'WP Global Stylesheet requires WPGraphQL plugin to be installed and activated.', 'hwp-global-stylesheet' ); ?></p>
</div>
<?php
}
}

/**
* Registers a field on the RootQuery called "globalStylesheet" which
* returns the stylesheet resulting of merging core, theme, and user data.
*
* @return void
*/
public function register_global_stylesheet_field() {
register_graphql_enum_type(
'GlobalStylesheetTypesEnum',
[
'description' => __( 'Types of styles to load', 'hwp-global-stylesheet' ),
'values' => [
'VARIABLES' => [
'value' => 'variables',
],
'PRESETS' => [
'value' => 'presets',
],
'STYLES' => [
'value' => 'styles',
],
'BASE_LAYOUT_STYLES' => [
'value' => 'base-layout-styles',
],
],
]
);

register_graphql_field(
'RootQuery',
'globalStylesheet',
[
'type' => 'String',
'args' => [
'types' => [
'type' => [ 'list_of' => 'GlobalStylesheetTypesEnum' ],
'description' => __( 'Types of styles to load.', 'hwp-global-stylesheet' ),
],
],
'description' => __( 'Returns the stylesheet resulting of merging core, theme, and user data.', 'hwp-global-stylesheet' ),
'resolve' => function( $root, $args, $context, $info ) {
$types = $args['types'] ?? null;

// Check if wp_get_global_stylesheet function exists (WordPress 5.9+)
if ( function_exists( 'wp_get_global_stylesheet' ) ) {
return wp_get_global_stylesheet( $types );
} else {
return '/* wp_get_global_stylesheet function is not available. Your WordPress version might be too old. */';
}
},
]
);
}
}

// Initialize the plugin
add_action( 'plugins_loaded', function() {
WP_Global_Stylesheet::get_instance();
});
7 changes: 7 additions & 0 deletions examples/next/wp-theme-rendered-blocks/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
6 changes: 6 additions & 0 deletions examples/next/wp-theme-rendered-blocks/next.config.mjs
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;
Loading