Summary: Learning about Block Theme Supports and Block Notices and its types.
Theme Supports
Block themes in WordPress are themes built entirely with blocks, allowing full customization through the Gutenberg block editor. Block themes take full advantage of the WordPress Full Site Editing (FSE) features, enabling users to modify their entire site using the block editor. This is different from traditional themes, where customizations were often handled through the Customizer, theme options, and template files. Block themes are designed with simplicity and flexibility in mind.
Block themes utilize blocks to define every aspect of a theme, from headers and footers to post templates. Block themes are structured differently from traditional themes and rely on block.json
files to register blocks and block templates.
Block themes utilize blocks to define every aspect of a theme, from headers and footers to post templates. Block themes are structured differently from traditional themes and rely on block.json
files to register blocks and block templates.
style.css
: As with any WordPress theme, block themes still include this file for theme information.functions.php
: Optional but often used for adding theme supports, custom functions, or registering assets.theme.json
: A core file used to define the global styles, settings, and block editor features.- Template Files: These are usually
.html
files rather than PHP files (e.g.,index.html
,header.html
,footer.html
, etc.).
theme.json
The theme.json
file is crucial for block themes. It allows theme developers to set global styles and define block behaviors for the entire site, offering full control over the look and feel of blocks.
{
"version": 2,
"settings": {
"color": {
"palette": [
{
"slug": "primary",
"color": "#ff0000",
"name": "Primary"
}
],
"custom": false,
"customGradient": false
},
"typography": {
"fontSizes": [
{
"slug": "small",
"size": "12px",
"name": "Small"
}
]
}
},
"styles": {
"blocks": {
"core/paragraph": {
"typography": {
"fontSize": "16px"
}
}
}
}
}
- Global Settings: Define site-wide typography, colors, layout options, etc.
- Block Settings: Override specific block styles and behaviors globally.
- Version Control: The
version
key (set to 2 for block themes) allows WordPress to know how to interpret the file.
Templates and Template Parts
In block themes, templates and template parts are .html
files. These files define the structure of different parts of our theme.
index.html
: The main template file, similar toindex.php
in traditional themes.header.html
andfooter.html
: Template parts for the header and footer, respectively.single.html
: Template for single posts.page.html
: Template for individual pages.
We can create custom templates for specific post types, categories, or pages by naming the template files appropriately (e.g., single-{post-type}.html
, category-{slug}.html
).
Block Registration:
Blocks in a block theme can be registered via the block.json
file for each custom block.
{
"apiVersion": 2,
"name": "mytheme/test-block",
"title": "Test Block",
"category": "text",
"icon": "smiley",
"description": "A test block for demonstration.",
"supports": {
"html": false
},
"editorScript": "file:./build/index.js"
}
name
: The block’s unique identifier (namespace/block-name).title
: The display title in the block editor.category
: Defines where the block will appear in the block inserter.supports
: Various block-level supports (e.g., custom HTML, alignments, etc.).editorScript
: The JavaScript file that enqueues the block script in the editor.
Full Site Editing (FSE)
Block themes enable Full Site Editing, which allows users to edit every part of their theme, including headers, footers, sidebars, and templates, directly from the WordPress block editor.
- Template Editing: Users can create, edit, and customize templates in the block editor.
- Reusable Block Patterns: These are groups of blocks that can be reused across different templates and pages.
- Global Styles: Styles can be applied globally via the block editor, allowing for site-wide design consistency.
Theme Support
Block themes require specific theme support options enabled in the functions.php
file to ensure the block editor functions correctly.
function mytheme_support() {
// Add support for block styles.
add_theme_support( 'wp-block-styles' );
// Add support for full and wide align images.
add_theme_support( 'align-wide' );
// Add support for editor styles.
add_theme_support( 'editor-styles' );
add_editor_style( 'style.css' );
// Add support for custom color palettes.
add_theme_support( 'editor-color-palette', array(
array(
'name' => __( 'Primary', 'mytheme' ),
'slug' => 'primary',
'color' => '#0073aa',
),
) );
}
add_action( 'after_setup_theme', 'mytheme_support' );
Block Patterns
Block patterns are predefined block layouts that users can insert into pages or posts. They simplify creating complex layouts.
- Define block patterns in a PHP file.
- Register block patterns in
functions.php
using theregister_block_pattern()
function.
register_block_pattern(
'mytheme/my-pattern',
array(
'title' => __( 'Two Columns', 'mytheme' ),
'description' => _x( 'Two columns with image and text', 'Block pattern description', 'mytheme' ),
'content' => "<!-- wp:columns -->\n<div class=\"wp-block-columns\"><!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:image --><figure class=\"wp-block-image\"><img src=\"/path-to-image.jpg\"/></figure><!-- /wp:image --></div><!-- /wp:column -->\n\n<!-- wp:column -->\n<div class=\"wp-block-column\"><!-- wp:paragraph --><p>Lorem ipsum dolor sit amet.</p><!-- /wp:paragraph --></div><!-- /wp:column --></div><!-- /wp:columns -->",
)
);
Block Notices
Block notices are a part of the broader ecosystem of block development in WordPress, particularly when developing custom blocks or working with the Gutenberg editor. Block notices are used to provide feedback, warnings, errors, or success messages to users when they interact with blocks. This could involve validation, user actions, or general information about the block’s status. Block notices are crucial for improving the user experience by clearly communicating the state of the editor or a specific block.
Block notices are alerts or messages that appear in the Gutenberg block editor to inform users of important events, errors, or status updates. They may notify users about validation issues, block errors, successful actions, or any other critical information. These notices are typically temporary and can be dismissed by the user.
- Error messages when a block encounters a problem.
- Warnings or validations, such as if a block’s settings are misconfigured.
- Success messages after an action is completed (e.g., after saving block settings).
- Informational messages about a feature or block usage.
The @wordpress/notices
Package
WordPress provides the @wordpress/notices
package to handle block notices. This package includes functions that allow developers to create, manage, and display notices in the block editor.
npm install @wordpress/notices --save
Types of Notices
- Success Notice: Indicates that an action was successful (e.g., block saved or updated).
- Error Notice: Communicates an error that needs the user’s attention.
- Warning Notice: Shows warnings about potential issues that may need fixing.
- Info Notice: Provides informational or neutral messages to the user.
Displaying Notices
To display notices, we can use the @wordpress/notices
package in our custom block or Gutenberg plugin. The createNotice
function is the core function for adding notices.
import { createNotice } from '@wordpress/notices';
// Add a success notice
createNotice(
'success', // Type of the notice
'Your block has been updated successfully!', // Message
{
isDismissible: true, // Optional, whether the notice can be dismissed
type: 'snackbar', // Optional, style of notice (e.g., snackbar, default)
id: 'block-update-notice' // Optional, unique ID for this notice
}
);
'success'
: For successful actions.'error'
: For error messages.'warning'
: For warnings about potential issues.'info'
: For general informational messages.
isDismissible
: Whether the notice can be closed by the user. Defaults totrue
.type
: Defines the style of the notice. For instance,snackbar
notices appear briefly at the bottom of the editor.id
: The unique identifier for a notice, useful for removing or updating a specific notice later.
Removing a Notice
To remove a notice, we can use the removeNotice
function and pass the id
of the notice we wish to remove.
import { removeNotice } from '@wordpress/notices';
// Remove the notice with ID 'block-update-notice'
removeNotice( 'block-update-notice' );
Updating a Notice
To update an existing notice, we can first remove it and then create a new notice with the updated message or options.
// Remove the old notice
removeNotice( 'block-update-notice' );
// Add a new notice with the updated message
createNotice(
'success',
'The block has been updated successfully and changes were saved.',
{ id: 'block-update-notice' }
);
Notice Placement
Notices can be placed in different parts of the block editor. By default, notices are displayed in the editor’s main notice area, but we can use the type
parameter to control the placement and style.
'default'
: Standard notice that appears at the top of the screen.'snackbar'
: A smaller, temporary notice that appears briefly at the bottom of the screen.
createNotice(
'success',
'The block settings have been updated.',
{ type: 'snackbar' }
);
Notice Action Buttons
We can add action buttons to our notices to allow users to perform additional tasks directly from the notice. This can be useful for guiding users through workflows or letting them fix issues without leaving the current page.
createNotice(
'error',
'There was an issue saving your block settings.',
{
actions: [
{
label: 'Retry',
onClick: () => { console.log( 'Retrying save...' ); }
},
{
label: 'Cancel',
onClick: () => { console.log( 'Cancelled' ); }
}
]
}
);
actions
: An array of button objects that define thelabel
(button text) and theonClick
function (what happens when the button is clicked).
Notices for Validation
Block notices can be used for validation purposes to warn users when they have misconfigured a block or entered invalid data.
const validateUrl = ( url ) => {
const isValid = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test( url );
if ( ! isValid ) {
createNotice(
'error',
'Invalid URL. Please enter a valid web address.',
{ id: 'url-validation-error' }
);
}
};
Notices for Asynchronous Actions
We might want to show notices while performing asynchronous tasks, such as saving block data to an external API.
const saveData = async () => {
try {
createNotice( 'info', 'Saving block data...' );
await apiSaveBlockData(); // Async operation
createNotice( 'success', 'Block data saved successfully!' );
} catch ( error ) {
createNotice( 'error', 'Failed to save block data.' );
}
};
Persistent Notices
If we want to show a persistent notice that remains visible until explicitly dismissed, we can set the isDismissible
option to false
.
createNotice(
'warning',
'This block contains deprecated settings. Please update.',
{
isDismissible: false,
id: 'deprecated-block-warning'
}
);
Leave a Reply