Summary: Learning about WordPress Core Data and Block Types Data.
WordPress Core Data
WordPress Core Data is a JavaScript package that offers a structured way to access, modify, and manage data in WordPress, particularly for block development in the Gutenberg editor. It provides an abstraction over the REST API, making it easier to interact with WordPress content and settings without having to manually deal with API endpoints.
WordPress Core Data refers to a set of utilities that allow developers to access and manipulate WordPress data from within the browser using JavaScript. It is particularly useful for Gutenberg block development as it powers most of the interactions that happen inside the editor.
Core Data can be accessed using the @wordpress/data
package, which provides data stores that let us read and write information from various parts of the WordPress ecosystem. These stores are essentially pieces of state (modeled as JavaScript objects) that are updated reactively.
It integrates with other packages like @wordpress/api-fetch
(for REST API calls) and is heavily used by the @wordpress/block-editor
package to allow dynamic interaction between blocks, posts, users, settings, etc.
Stores
In WordPress Core Data, a store is a JavaScript object that holds the state of a specific section of WordPress. Each store represents a particular set of data. Stores are identified by their namespaces (e.g., core
, core/block-editor
), and developers can interact with them using functions like select
, dispatch
, and subscribe
.
- Select: Used to retrieve data from a store.
- Dispatch: Used to send actions to modify or request an update to a store.
- Subscribe: Allows us to watch for changes in a store and respond reactively.
core
: The primary store for interacting with posts, pages, taxonomies, users, media, and more.core/edit-post
: Store for editing post-related data (like post settings, current post ID, etc.).core/block-editor
: Store for interacting with block editor data, like block selection, block attributes, and block structure.
Selectors
Selectors are functions used to retrieve data from a store. They allow us to query the state of WordPress (e.g., fetching the current post, list of users, block attributes). Selectors are non-destructive, meaning they don’t modify the state but provide read-only access.
// Example: Get the current post ID from the core editor store.
const postId = wp.data.select('core/editor').getCurrentPostId();
Actions
Actions represent events or tasks that modify the state of a store. When an action is dispatched, it triggers a change in the store. We can think of them as commands or operations that tell WordPress what to do. Actions are dispatched using the dispatch
function.
// Example: Update the title of a post
wp.data.dispatch('core/editor').editPost({ title: 'New Post Title' });
Resolvers
Resolvers are functions used to manage asynchronous data. If a piece of data is not available in the store yet (e.g., if it needs to be fetched from the REST API), a resolver will trigger a request and update the store once the data is retrieved. Resolvers are called implicitly by selectors when needed.
Accessing Post Data
When developing blocks, we often need to retrieve post data (such as post ID, title, content, etc.) or other WordPress-related information. Using the Core Data system, we can select and update this data directly within our block.
import { useSelect } from '@wordpress/data';
const MyBlock = () => {
const post = useSelect((select) => {
return select('core/editor').getCurrentPost();
});
return <div>{post.title}</div>;
};
Managing Block States
Blocks often need to interact with other blocks or respond to changes in the editor’s state. For instance, we may want to update a block’s attributes or react to the current selection of blocks.
- Block Selection: Using the
core/block-editor
store, we can detect when a block is selected and retrieve information about the currently selected block.
const selectedBlock = wp.data.select('core/block-editor').getSelectedBlock();
- Updating Block Attributes: To update block attributes dynamically, we can dispatch actions to the
core/block-editor
store.
wp.data.dispatch('core/block-editor').updateBlockAttributes(blockId, { myAttribute: 'new value' });
Saving and Editing Posts
The core/editor
store is particularly useful for saving or editing post data, like updating the post title, content, or metadata programmatically from a block.
wp.data.dispatch('core/editor').editPost({ title: 'New Title' });
wp.data.dispatch('core/editor').savePost();
Working with the Media Library
Fetching and selecting media is a common task in block development, especially for image or video-related blocks. The core
store provides functions to access the media library and retrieve media data.
const media = wp.data.select('core').getMediaItems({ search: 'my-image' });
User Data
In cases where we need to interact with user data (for example, to display the current author’s name), the core
store allows us to fetch users and their associated information.
const currentUser = wp.data.select('core').getCurrentUser();
Custom Data Stores
For more advanced block development scenarios, we might want to define our own custom data stores. This can be useful if we have a unique state management need that isn’t covered by the existing Core Data stores.
- Creating a Custom Store: We can register a new data store using the
registerStore
function from@wordpress/data
.
import { registerStore } from '@wordpress/data';
const DEFAULT_STATE = {
myData: [],
};
const myStore = registerStore('my-namespace/my-store', {
reducer(state = DEFAULT_STATE, action) {
switch (action.type) {
case 'SET_DATA':
return { ...state, myData: action.data };
}
return state;
},
actions: {
setData(data) {
return { type: 'SET_DATA', data };
},
},
selectors: {
getData(state) {
return state.myData;
},
},
});
Once registered, we can select from and dispatch to this custom store like any other:
const data = wp.data.select('my-namespace/my-store').getData();
wp.data.dispatch('my-namespace/my-store').setData(newData);
Block Types Data
The WordPress Block Types Data (core/blocks
) is a crucial part of the WordPress Core Data system, specifically designed for handling block types within the Gutenberg block editor. The core/blocks
store provides access to registered block types and helps manage various attributes and settings related to those blocks. As block development continues to expand, understanding how to interact with this store is essential for creating custom blocks and managing block functionality in WordPress.
The core/blocks
data store is primarily used for managing and retrieving information about blocks, including registered block types, their settings, and related metadata. This store interacts closely with the block editor’s rendering engine, allowing developers to register new blocks, retrieve registered block data, and perform actions like updating or unregistering blocks.
- Register, unregister, and retrieve block types.
- Get block type settings, categories, transforms, supports, and variations.
- Manage the dynamic behaviors of blocks (like transforming one block into another).
Block Types
In WordPress, a block type defines the structure and behavior of a block. It includes attributes like the block’s name, category, description, attributes, and more. The core/blocks
store is central to working with block types in WordPress. Block types are typically registered during plugin or theme initialization using the registerBlockType
function.
name
: A unique identifier for the block.title
: A human-readable title.category
: The category to which the block belongs (e.g., common, formatting).attributes
: Data structure that holds the block’s attributes.supports
: Features the block supports (e.g., alignments, custom classes).edit
andsave
functions: Define how the block appears and functions in the editor and the front end.
Selectors
Selectors in the core/blocks
store allow developers to retrieve information about block types and block categories. They are the main tool used to access registered block types and other related data.
getBlockType
: Retrieves the data of a specific block type by its name.
const blockType = wp.data.select('core/blocks').getBlockType('core/paragraph');
console.log(blockType); // Outputs the block type definition for paragraph block.
getBlockTypes
: Retrieves all registered block types.
const blockTypes = wp.data.select('core/blocks').getBlockTypes();
console.log(blockTypes); // Outputs an array of all block types.
getBlockSupport
: Retrieves support features for a block (such as alignments, etc.).
const supportsAlignment = wp.data.select('core/blocks').getBlockSupport('core/paragraph', 'align');
console.log(supportsAlignment); // true if the block supports alignment.
hasBlockSupport
: Checks if a particular block supports a specific feature.
const hasSupport = wp.data.select('core/blocks').hasBlockSupport('core/paragraph', 'align');
console.log(hasSupport); // Returns true or false.
getBlockVariations
: Retrieves block variations for a specific block type.
const variations = wp.data.select('core/blocks').getBlockVariations('core/button');
console.log(variations); // Outputs an array of variations for the button block.
Actions
The core/blocks
store provides various actions to manage blocks and block types. These actions are particularly useful when we are dynamically adding, modifying, or removing blocks during runtime.
registerBlockType
: Registers a new block type with a specific name and settings. This is the most commonly used action when developing custom blocks.
wp.blocks.registerBlockType('my-plugin/my-custom-block', {
title: 'My Custom Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit: (props) => {
return <p>Hello from the editor!</p>;
},
save: (props) => {
return <p>Hello from the front end!</p>;
},
});
unregisterBlockType
: Unregisters an existing block type by its name.
wp.data.dispatch('core/blocks').unregisterBlockType('core/paragraph');
setBlockTypes
: A lower-level action that allows we to directly set the registered block types.
Resolvers
Resolvers in the core/blocks
store are used to fetch block types or block metadata asynchronously, typically when fetching data from the server. While these are implicitly called when needed, developers can leverage them for custom workflows.
Working with Block Categories
Block categories are a way to group blocks within the editor’s block picker. Categories help organize blocks and make it easier for users to find the right block when editing content.
getCategories
: Retrieves all available block categories.
const categories = wp.data.select('core/blocks').getCategories();
console.log(categories);
addBlockCategories
: Dynamically adds new block categories. Useful if we are registering custom blocks and want them in a new category.
wp.data.dispatch('core/blocks').addBlockCategories([
{
slug: 'custom-category',
title: 'Custom Blocks',
icon: 'star-filled',
},
]);
Block Variations
Block variations are an extension of block types that allow us to create multiple versions of a block with different default attributes or settings. Variations are particularly useful for blocks like buttons, where the block structure remains the same, but the style or content changes based on the selected variation.
getBlockVariations
: Retrieves variations for a specific block.
const variations = wp.data.select('core/blocks').getBlockVariations('core/button');
console.log(variations); // Outputs the available button variations.
registerBlockVariation
: Registers a new variation for a block type.
wp.blocks.registerBlockVariation('core/button', {
name: 'primary-button',
title: 'Primary Button',
attributes: { className: 'primary-button' },
innerHTML: 'Click Me',
});
unregisterBlockVariation
: Unregisters a specific block variation.
wp.data.dispatch('core/blocks').unregisterBlockVariation('core/button', 'primary-button');
Block Transforms
Block transforms allow users to convert one block type into another. For example, a user can convert a paragraph block into a heading block. Transforms are typically handled by the editor’s UI, but developers can define their own custom transforms for blocks.
getBlockTransforms
: Retrieves available transforms for a block type.
const transforms = wp.data.select('core/blocks').getBlockTransforms('from', 'core/paragraph');
console.log(transforms); // Lists all the blocks the paragraph block can be transformed into.
registerBlockTransform
: Registers a custom block transform.
wp.blocks.registerBlockTransform('core/paragraph', {
from: [
{
type: 'block',
blocks: ['core/heading'],
transform: (attributes) => {
return wp.blocks.createBlock('core/heading', { content: attributes.content });
},
},
],
});
Leave a Reply