-
Notifications
You must be signed in to change notification settings - Fork 2
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
Changes from 3 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
10 changes: 10 additions & 0 deletions
10
examples/next/render-blocks-pages-router/example.env.local
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,10 @@ | ||
# WordPress GraphQL Endpoint | ||
WORDPRESS_GRAPHQL_ENDPOINT=https://your-wp-site.com/graphql | ||
|
||
# Global Stylesheet settings | ||
WP_GLOBAL_STYLES_OUTPUT=public/hwp-global-styles.css | ||
WP_GLOBAL_STYLES_TYPES=variables,presets,styles,base-layout-styles | ||
WP_GLOBAL_STYLES_MINIFY=true | ||
|
||
# Set to true for verbose output | ||
WP_GLOBAL_STYLES_VERBOSE=false |
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
163 changes: 163 additions & 0 deletions
163
examples/next/render-blocks-pages-router/scripts/fetchWpGlobalStyles.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,163 @@ | ||
#!/usr/bin/env node | ||
|
||
const fs = require('fs'); | ||
const path = require('path'); | ||
const { program } = require('commander'); | ||
|
||
// Load environment variables from .env.local if not in production | ||
if (process.env.NODE_ENV !== 'production') { | ||
try { | ||
const dotenv = require('dotenv'); | ||
// First check for .env.local, then fallback to .env | ||
const envFile = fs.existsSync(path.resolve(process.cwd(), '.env.local')) | ||
? '.env.local' | ||
: '.env'; | ||
|
||
dotenv.config({ path: path.resolve(process.cwd(), envFile) }); | ||
} catch (error) { | ||
console.warn('dotenv is not installed. Environment variables must be set manually.'); | ||
} | ||
} | ||
|
||
// Configure CLI options with defaults from environment variables | ||
program | ||
.name('fetch-wp-styles') | ||
.description('Fetch WordPress global stylesheets for Next.js integration') | ||
.option( | ||
'-e, --endpoint <url>', | ||
'WordPress GraphQL endpoint URL', | ||
process.env.WORDPRESS_GRAPHQL_ENDPOINT | ||
) | ||
.option( | ||
'-o, --output <path>', | ||
'Output CSS file path', | ||
process.env.WP_GLOBAL_STYLES_OUTPUT || 'public/hwp-global-styles.css' | ||
) | ||
.option( | ||
'-t, --types <types...>', | ||
'Style types to fetch (variables, presets, styles, base-layout-styles)', | ||
parseStyleTypes(process.env.WP_GLOBAL_STYLES_TYPES) | ||
) | ||
.option( | ||
'-v, --verbose', | ||
'Show verbose output', | ||
process.env.WP_GLOBAL_STYLES_VERBOSE === 'true' | ||
) | ||
.option( | ||
'--minify <boolean>', | ||
'Minify CSS output', | ||
parseBooleanOption(process.env.WP_GLOBAL_STYLES_MINIFY, process.env.NODE_ENV === 'production') | ||
) | ||
.parse(process.argv); | ||
|
||
const options = program.opts(); | ||
|
||
// Validate required options | ||
if (!options.endpoint) { | ||
console.error('Error: WordPress GraphQL endpoint is required. Use --endpoint option or set WORDPRESS_GRAPHQL_ENDPOINT env variable.'); | ||
process.exit(1); | ||
} | ||
|
||
async function fetchGlobalStyles() { | ||
const { endpoint, output, types, verbose, minify } = options; | ||
|
||
if (verbose) { | ||
console.log(`Fetching global styles from: ${endpoint}`); | ||
console.log(`Requested style types: ${types.join(', ')}`); | ||
console.log(`Output will be saved to: ${output}`); | ||
console.log(`Minification enabled: ${minify}`); | ||
} | ||
|
||
// Convert type strings to enum values for the GraphQL query | ||
const typeEnums = types.map(type => { | ||
// Convert to uppercase and replace dashes with underscores for GraphQL enum format | ||
return type.toUpperCase().replace(/-/g, '_'); | ||
}); | ||
|
||
try { | ||
// Prepare the GraphQL query with type selection | ||
const query = ` | ||
query FetchGlobalStylesheet { | ||
globalStylesheet(types: [${typeEnums.join(', ')}]) | ||
} | ||
`; | ||
|
||
const response = await fetch(endpoint, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ query }), | ||
}); | ||
|
||
if (!response.ok) { | ||
throw new Error(`HTTP error! Status: ${response.status}`); | ||
} | ||
|
||
const json = await response.json(); | ||
|
||
if (json.errors) { | ||
throw new Error(`GraphQL errors: ${json.errors.map(e => e.message).join(', ')}`); | ||
} | ||
|
||
if (!json.data || !json.data.globalStylesheet) { | ||
throw new Error('No stylesheet data returned from the API'); | ||
} | ||
|
||
let styles = json.data.globalStylesheet; | ||
|
||
// Process the CSS if needed (minify, etc.) | ||
if (minify) { | ||
// Simple minification - remove comments, whitespace, and newlines | ||
styles = styles | ||
.replace(/\/\*[\s\S]*?\*\//g, '') // Remove comments | ||
.replace(/\s+/g, ' ') // Collapse whitespace | ||
.replace(/\s*([{}:;,])\s*/g, '$1') // Remove spaces around symbols | ||
.trim(); | ||
} | ||
|
||
// Make sure the directory exists | ||
const outputDir = path.dirname(output); | ||
fs.mkdirSync(path.resolve(process.cwd(), outputDir), { recursive: true }); | ||
|
||
// Write the CSS file | ||
fs.writeFileSync(path.resolve(process.cwd(), output), styles); | ||
|
||
if (verbose) { | ||
console.log(`Global styles successfully saved to: ${output} (${styles.length} bytes)`); | ||
} else { | ||
console.log(`Global styles successfully saved to: ${output}`); | ||
} | ||
} catch (error) { | ||
console.error('Error fetching global styles:', error); | ||
process.exit(1); | ||
} | ||
} | ||
|
||
// Helper function to parse style types from env variable | ||
function parseStyleTypes(typesString) { | ||
if (!typesString) { | ||
return ['variables', 'presets', 'styles', 'base-layout-styles']; | ||
} | ||
|
||
return typesString.split(',').map(type => type.trim()); | ||
} | ||
|
||
// Helper function to parse boolean options. | ||
function parseBooleanOption(value, defaultValue = false) { | ||
if (value === undefined || value === null) { | ||
return defaultValue; | ||
} | ||
|
||
if (typeof value === 'boolean') { | ||
return value; | ||
} | ||
|
||
if (typeof value === 'string') { | ||
return value.toLowerCase() === 'true'; | ||
} | ||
|
||
return Boolean(value); | ||
} | ||
|
||
fetchGlobalStyles(); |
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
127 changes: 127 additions & 0 deletions
127
plugins/hwp-global-stylesheet/hwp-global-stylesheet.php
whoami-pwd marked this conversation as resolved.
Show resolved
Hide resolved
|
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,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(); | ||
}); |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.