This document defines the "gold standard" patterns and practices for block development based off analysis of key blocks in PRC Block Library. Blocks adhering to this standard are designed for maximum performance, extensibility, and maintainability, leveraging modern WordPress capabilities including the Interactivity API and Block Context. While this spec is not mandatory for all blocks, it serves as a guideline for new block development and a reference for migrating existing blocks to best practices. Additionally, this document should be thought of as a living document, evolving with the Gutenberg project's development.
Executive Summary
Our gold standard blocks represent a sophisticated approach to WordPress block development that prioritizes:
- Static HTML Generation: Save.js files that output minimal, semantic HTML structure
- Server-Side Enhancement: PHP render callbacks using WP_HTML_Tag_Processor for dynamic augmentation
- Interactivity API Integration: Modern WordPress interactivity for client-side behavior
- Context-Driven Architecture: Blocks that communicate via WordPress Block Context
- Core WordPress Standards: Maximum utilization of built-in color, typography, and spacing supports
Core Architectural Principles
1. Static HTML Foundation (save.js)
Gold standard blocks generate minimal, semantic HTML structure that serves as a foundation for server-side enhancement:
Key Patterns:
- Use semantic HTML elements appropriate for the content
- Leverage core WordPress color supports with intelligent separation of text/background colors
- Include placeholder elements that are dynamically populated server-side
- Maintain accessibility standards with proper ARIA attributes where needed
Example from form-input-checkbox/save.jsx:25-42:
const colorProps = getColorClassesAndStyles(attributes);
const backgroundColor = colorProps.style.backgroundColor;
const backgroundColorClass = colorProps?.className
?.split(' ')
.filter(
(className) =>
className.includes('-background-color') ||
className.includes('has-background')
);
const textColor = colorProps.style.color;
const textColorClass = colorProps?.className
?.split(' ')
.filter((className) => !backgroundColorClass.includes(className));
const blockProps = useBlockProps.save({
className: clsx('wp-block-prc-block-form-input-checkbox', textColorClass),
style: { color: textColor },
});
Example from tabs/save.jsx:15-21:
return (
<div {...blockProps}>
<h3 className="tabs__title">{title}</h3>
<ul className="tabs__list"></ul>
{innerBlocksProps.children}
</div>
);
2. Server-Side Enhancement with WP_HTML_Tag_Processor
Gold standard blocks use PHP render callbacks to intelligently augment the static HTML:
Key Patterns:
- Process HTML content using
WP_HTML_Tag_Processorfor precise element manipulation - Add Interactivity API directives dynamically
- Generate unique IDs and manage state initialization
- Intelligently splice dynamic content into placeholder elements
Example from form-input-checkbox/class-form-input-checkbox.php:54-74:
$tag = new \WP_HTML_Tag_Processor( $content );
$tag->next_tag( array( 'class_name' => 'wp-block-prc-block-form-input-checkbox' ) );
// Add directives to block wrapper
$tag->set_attribute( 'data-wp-on--mouseenter', $target_store . 'actions.onInputMouseEnter' );
$tag->set_attribute( 'data-wp-on--mouseleave', $target_store . 'actions.onInputMouseLeave' );
$tag->set_attribute( 'data-wp-class--is-error', $target_store . 'state.isInputError' );
// Get, store, and remove the id attribute from the block wrapper
$block_id = $tag->get_attribute( 'id' );
$tag->remove_attribute( 'id' );
if ( ! $block_id ) {
$block_id = wp_unique_id( 'prc-block-form-input-checkbox-' );
}
Example from tabs/class-tabs.php:243-247:
$content = preg_replace(
'/<ul\s+class="tabs__list">\s*<\/ul>/i',
'<div class="tabs__list" role="tablist">' . $tabs_list_markup . '</div>',
(string) $updated_content
);
3. Interactivity API Integration
Gold standard blocks implement modern WordPress Interactivity patterns:
Key Patterns:
- Namespace-based stores for encapsulation
- Context-aware state management
- Generator functions for cross-store communication
- Proper event handling with
withSyncEvent
Example from form-input-password/view.js:24-32:
const { actions, state } = store('prc-block/form-input-password', {
state: {
get id() {
return getContext()?.id || false;
},
get value() {
const { id } = state;
return state[id]?.value || '';
},
},
});
Example from tabs/view.js:115-127:
setActiveTab: (tabIndex, scrollToTab = false) => {
const context = getContext();
context.activeTabIndex = tabIndex;
if (scrollToTab) {
const tabId = state.tabsList[tabIndex].id;
const tabElement = document.getElementById(tabId);
if (tabElement) {
setTimeout(() => {
tabElement.scrollIntoView({ behavior: 'smooth' });
}, 100);
}
}
};
4. Block Context Architecture
Gold standard blocks use WordPress Block Context for parent-child communication:
Key Patterns:
- Parent blocks provide context via
providesContext - Child blocks consume context via
usesContext - Context enables dynamic relationships between blocks
Example from tab/block.json:133-135:
"providesContext": {
"tab/label": "label"
},
Sometimes context is injected server-side for dynamic values:
Example from core-tabs/class-core-tabs.php:133-153:
/**
* Add slugified label to context as tab/slug for children.
*
* @hook render_block_context
*
* @param array $context The current context.
* @param array $parsed_block The parsed block array.
* @return array Updated context.
*/
public function filter_render_block_context( array $context, array $parsed_block ): array {
if ( ( $parsed_block['blockName'] ?? '' ) !== 'prc-block/tab' ) {
return $context;
}
$attrs = $parsed_block['attrs'] ?? array();
$label = isset( $attrs['label'] ) ? wp_strip_all_tags( (string) $attrs['label'] ) : '';
if ( $label ) {
$label = str_replace( '&', 'and', $label );
$context['tab/slug'] = sanitize_title( $label );
}
return $context;
}
Example from core-tabs/tab-label-binding:14-26:
registerBlockBindingsSource({
name: 'tab/label',
usesContext: ['tab/label'],
getValues({ select, context }) {
const tabLabel = context['tab/label'];
if (tabLabel) {
return {
content: tabLabel,
};
}
return {
placeholder: __('Enter tab label', 'prc-quiz'),
};
},
});
5. Core WordPress Standards Utilization
Gold standard blocks maximize use of WordPress core supports:
Color Support Patterns:
- Intelligent separation of text and background colors
- Use of
__experimentalSkipSerializationfor custom processing - Selective application via CSS selectors
Example from form-input-checkbox/block.json:56-82:
"supports": {
"color": {
"background": true,
"text": true,
"link": true,
"__experimentalSkipSerialization": true
},
"selectors": {
"root": ".wp-block-prc-block-form-input-checkbox",
"color": {
"text": ".wp-block-prc-block-form-input-checkbox label",
"background": ".wp-block-prc-block-form-input-checkbox input"
}
}
}
Typography & Spacing Support Patterns:
- Granular control over font properties
- Comprehensive spacing options (padding, margin, blockGap)
- Experimental features enabled selectively
6. Advanced Features
Responsive Controls
Gold standard blocks implement responsive design patterns using WordPress core hooks and object structured attributes, like prc-block-library/src/show-more.
- Always device preview (desktop, tablet, mobile) contextually accurate controls in a toolbar and all contexts controls in a inspector sidebar.
Variations System
Gold standard blocks implement sophisticated variation patterns for different use cases:
Example from form-input-password/variations.js:11-30:
{
name: 'password-without-confirmation',
title: __('Password field', 'prc-block-library'),
attributes: {
className: 'password-without-confirmation',
includesConfirmation: false,
},
isDefault: true,
innerBlocks: [getTemplate()],
isActive: (attributes, variationAttributes) =>
variationAttributes.includesConfirmation === attributes.includesConfirmation,
}
State Management Patterns
- Instance-specific state management
- Cross-namespace communication via generator functions
- Proper cleanup and initialization callbacks
Accessibility Integration
- ARIA attributes managed dynamically
- Keyboard navigation support
- Focus management patterns
Implementation Checklist
When creating a new block following gold standard patterns:
Block Configuration (block.json)
- API version 3
- Comprehensive supports configuration
- Selective color/typography supports
- Interactivity enabled when needed
- Context relationships defined (providesContext/usesContext) if applicable
- Proper textdomain and script/style references
Static HTML Foundation (save.jsx)
- Minimal, semantic HTML structure
- Intelligent use of core WordPress supports
- Placeholder elements for dynamic content
- Proper className patterns
- Accessibility attributes where appropriate
Server-Side Enhancement (PHP Class)
- WP_HTML_Tag_Processor for content manipulation
- Interactivity API directives added dynamically
- Unique ID generation and management
- State initialization via
wp_interactivity_state() - Graceful fallback handling
Client-Side Interactivity (view.js)
- Namespaced store definition
- Context-aware state getters
- Event handlers with
withSyncEvent - Generator functions for cross-store communication
- Proper initialization callbacks
Styling Architecture
- CSS custom properties for theming
- BEM-style class naming conventions
- Responsive design patterns
- Integration with WordPress design tokens
Quality Standards
Code Quality
- Modern JavaScript (ES6+) patterns
- Proper error handling and validation
- Comprehensive inline documentation
- TypeScript-style JSDoc annotations where applicable
Performance
- Minimal JavaScript payload
- Efficient DOM manipulation via WP_HTML_Tag_Processor
- Proper event handling to avoid memory leaks
- Lazy loading of non-critical functionality
Accessibility
- WCAG 2.1 AA compliance
- Proper ARIA attributes
- Keyboard navigation support
- Screen reader compatibility
Extensibility
- Hook-based architecture for modifications
- Custom events for third-party integration
- Modular component structure
- Clear extension points
Migration Path
When updating existing blocks to gold standard:
- Assessment: Evaluate current implementation against checklist
- Save.js Refactoring: Move to minimal HTML approach
- Server-Side Implementation: Add PHP render callback with WP_HTML_Tag_Processor, if a render.php file exists move to a render callback and remove the old render.php file.
- Interactivity Migration: Convert to modern Interactivity API patterns
- Context Integration: Implement parent-child communication patterns
- Core Supports: Maximize use of WordPress built-in supports
- Testing: Comprehensive testing across use cases and devices
Conclusion
The gold standard represents the evolution of WordPress block development toward more maintainable, performant, and extensible patterns. By following these specifications, blocks will be:
- Future-proof: Aligned with WordPress core direction
- Performant: Optimized for both server and client-side execution
- Accessible: Meeting modern web accessibility standards
- Extensible: Designed for customization and third-party integration
- Maintainable: Clear patterns and comprehensive documentation
This standard should be viewed as a living document, evolving alongside the Gutenberg project's development.