
Security News
GitHub Actions Pricing Whiplash: Self-Hosted Actions Billing Change Postponed
GitHub postponed a new billing model for self-hosted Actions after developer pushback, but moved forward with hosted runner price cuts on January 1.
@wordpress/blocks
Advanced tools
"Block" is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage. The idea combines concepts of what in WordPress today we achieve with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience.
For more context, refer to What Are Little Blocks Made Of? from the Make WordPress Design blog.
Install the module
npm install @wordpress/blocks --save
This package assumes that your code will run in an ES2015+ environment. If you're using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.
Given a block object, returns a copy of the block object, optionally merging new attributes and/or replacing its inner blocks.
Parameters
Object: Block instance.Object: Block attributes.?Array: Nested blocks.Returns
Object: A cloned block.Returns a block object given its type and attributes.
Parameters
string: Block name.Object: Block attributes.?Array: Nested blocks.Returns
Object: Block object.Given an array of InnerBlocks templates or Block Objects, returns an array of created Blocks from them. It handles the case of having InnerBlocks as Blocks by converting them to the proper format to continue recursively.
Parameters
Array: Nested blocks or InnerBlocks templates.Returns
Object[]: Array of Block objects.Checks whether a list of blocks matches a template by comparing the block names.
Parameters
Array: Block list.Array: Block template.Returns
boolean: Whether the list of blocks matches a templates.Given an array of transforms, returns the highest-priority transform where the predicate function returns a truthy value. A higher-priority transform is one with a lower priority value (i.e. first in priority order). Returns null if the transforms set is empty or the predicate function returns a falsey value for all entries.
Parameters
Object[]: Transforms to search.Function: Function returning true on matching transform.Returns
?Object: Highest-priority transform candidate.Returns the block attributes of a registered block node given its type.
Parameters
string|Object: Block type or name.string|Node: Raw block content.?Object: Known block attributes (from delimiters).Returns
Object: All block attributes.Filter block attributes by role and return their names.
Parameters
string: Block attribute's name.string: The role of a block attribute.Returns
string[]: The attribute names that have the provided role.Returns a registered block bindings source by its name.
Parameters
string: Block bindings source name.Returns
?Object: Block bindings source.Changelog
6.7.0 Introduced in WordPress core.
Returns all registered block bindings sources.
Returns
Array: Block bindings sources.Changelog
6.7.0 Introduced in WordPress core.
Given a block object, returns the Block's Inner HTML markup.
Parameters
Object: Block instance.Returns
string: HTML.Returns the block's default classname from its name.
Parameters
string: The block name.Returns
string: The block's default class.Create a block object from the example API.
Parameters
string:Object:Returns
Object: block.Returns the block's default menu item classname from its name.
Parameters
string: The block name.Returns
string: The block's default menu item class.Returns the block support value for a feature, if defined.
Parameters
(string|Object): Block name or type objectstring: Feature to retrieve*: Default value to return if not explicitly definedReturns
?*: Block support valueReturns normal block transforms for a given transform direction, optionally for a specific block by name, or an empty array if there are no transforms. If no block name is provided, returns transforms for all blocks. A normal transform object includes blockName as a property.
Parameters
string: Transform direction ("to", "from").string|Object: Block type or name.Returns
Array: Block transforms for direction.Returns a registered block type.
Parameters
string: Block name.Returns
?Object: Block type.Returns all registered blocks.
Returns
Array: Block settings.Returns an array with the child blocks of a given block.
Parameters
string: Name of block (example: “latest-posts”).Returns
Array: Array of child block names.Retrieves the default block name.
Returns
?string: Block name.Retrieves name of block handling non-block content, or undefined if no handler has been defined.
Returns
?string: Block name.Retrieves name of block used for handling grouping interactions.
Returns
?string: Block name.Undocumented declaration.
Returns an array of block types that the set of blocks received as argument can be transformed into.
Parameters
Array: Blocks array.Returns
Array: Block types that the blocks argument can be transformed to.Given a block type containing a save render implementation and attributes, returns the static markup to be saved.
Parameters
string|Object: Block type or name.Object: Block attributes.?Array: Nested blocks.Returns
string: Save content.Given a block type containing a save render implementation and attributes, returns the enhanced element to be saved or string when raw HTML expected.
Parameters
string|Object: Block type or name.Object: Block attributes.?Array: Nested blocks.Returns
Object|string: Save element or raw HTML string.Retrieves name of block handling unregistered block types, or undefined if no handler has been defined.
Returns
?string: Block name.Returns true if the block defines support for a feature, or false otherwise.
Parameters
(string|Object): Block name or type object.string: Feature to test.boolean: Whether feature is supported by default if not explicitly defined.Returns
boolean: Whether block supports feature.Returns a boolean indicating if a block has child blocks or not.
Parameters
string: Name of block (example: “latest-posts”).Returns
boolean: True if a block contains child blocks and false otherwise.Returns a boolean indicating if a block has at least one child block with inserter support.
Parameters
string: Block type name.Returns
boolean: True if a block contains at least one child blocks with inserter support and false otherwise.Determines whether or not the given block is a reusable block. This is a special block type that is used to point to a global block stored via the API.
Parameters
Object: Block or Block Type to test.Returns
boolean: Whether the given block is a reusable block.Determines whether or not the given block is a template part. This is a special block type that allows composing a page template out of reusable design elements.
Parameters
Object: Block or Block Type to test.Returns
boolean: Whether the given block is a template part.Determines whether the block's attributes are equal to the default attributes which means the block is unmodified.
Parameters
WPBlock: Block Object.?string: Optional role to filter attributes for modification check.Returns
boolean: Whether the block is an unmodified block.Determines whether the block is a default block and its attributes are equal to the default attributes which means the block is unmodified.
Parameters
WPBlock: Block Object?string: Optional role to filter attributes for modification check.Returns
boolean: Whether the block is an unmodified default block.Deprecated Use validateBlock instead to avoid data loss.
Returns true if the parsed block is valid given the input content. A block is considered valid if, when serialized with assumed attributes, the content matches the original value.
Logs to console in development environments when invalid.
Parameters
string|Object: Block type.Object: Parsed block attributes.string: Original block content.Returns
boolean: Whether block is valid.Function that checks if the parameter is a valid icon.
Parameters
*: Parameter to be checked.Returns
boolean: True if the parameter is a valid icon and false otherwise.Function that receives an icon as set by the blocks during the registration and returns a new icon object that is normalized so we can rely on just on possible icon structure in the codebase.
Parameters
WPBlockTypeIconRender: Render behavior of a block type icon; one of a Dashicon slug, an element, or a component.Returns
WPBlockTypeIconDescriptor: Object describing the icon.Utilizes an optimized token-driven parser based on the Gutenberg grammar spec defined through a parsing expression grammar to take advantage of the regular cadence provided by block delimiters -- composed syntactically through HTML comments -- which, given a general HTML document as an input, returns a block list array representation.
This is a recursive-descent parser that scans linearly once through the input document. Instead of directly recursing it utilizes a trampoline mechanism to prevent stack overflow. This initial pass is mainly interested in separating and isolating the blocks serialized in the document and manifestly not in the content within the blocks.
Related
Parameters
string: The post content.ParseOptions: Extra options for handling block parsing.Returns
Array: Block list.Given a block's raw content and an attribute's schema returns the attribute's value depending on its source.
Parameters
string|Node: Block's raw content.Object: Attribute's schema.Returns
*: Attribute value.Converts an HTML string to known blocks. Strips everything else.
Parameters
Object:[string]: The HTML to convert.[string]: Plain text version.[string]: Handle content as blocks or inline content. _ 'AUTO': Decide based on the content passed. _ 'INLINE': Always handle as inline content, and return string. * 'BLOCKS': Always handle as blocks, and return array of blocks.[Array]: The tag into which content will be inserted.Returns
Array|string: A list of blocks or a string, depending on handlerMode.Undocumented declaration.
Converts an HTML string to known blocks.
Parameters
Object:string: The HTML to convert.Returns
Array: A list of blocks.Registers a new block bindings source with an object defining its behavior. Once registered, the source is available to be connected to the supported block attributes.
Usage
import { _x } from '@wordpress/i18n';
import { registerBlockBindingsSource } from '@wordpress/blocks';
registerBlockBindingsSource( {
name: 'plugin/my-custom-source',
label: _x( 'My Custom Source', 'block bindings source' ),
usesContext: [ 'postType' ],
getValues: getSourceValues,
setValues: updateMyCustomValuesInBatch,
canUserEditValue: () => true,
} );
Parameters
WPBlockBindingsSource: Object describing a block bindings source.Changelog
6.7.0 Introduced in WordPress core.
Registers a new block collection to group blocks in the same namespace in the inserter.
Usage
import { __ } from '@wordpress/i18n';
import { registerBlockCollection, registerBlockType } from '@wordpress/blocks';
// Register the collection.
registerBlockCollection( 'my-collection', {
title: __( 'Custom Collection' ),
} );
// Register a block in the same namespace to add it to the collection.
registerBlockType( 'my-collection/block-name', {
title: __( 'My First Block' ),
edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
save: () => <div>'Hello from the saved content!</div>,
} );
Parameters
string: The namespace to group blocks by in the inserter; corresponds to the block namespace.Object: The block collection settings.string: The title to display in the block inserter.[Object]: The icon to display in the block inserter.Registers a new block style for the given block types.
For more information on connecting the styles with CSS the official documentation.
Usage
import { __ } from '@wordpress/i18n';
import { registerBlockStyle } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
registerBlockStyle( 'core/quote', {
name: 'fancy-quote',
label: __( 'Fancy Quote' ),
} );
} }
>
{ __( 'Add a new block style for core/quote' ) }
</Button>
);
};
Parameters
string|Array: Name of blocks e.g. “core/latest-posts” or ["core/group", "core/columns"].Object: Object containing name which is the class name applied to the block and label which identifies the variation to the user.Registers a new block provided a unique name and an object defining its behavior. Once registered, the block is made available as an option to any editor interface where blocks are implemented.
For more in-depth information on registering a custom block see the Create a block tutorial.
Usage
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
registerBlockType( 'namespace/block-name', {
title: __( 'My First Block' ),
edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
save: () => <div>Hello from the saved content!</div>,
} );
Parameters
string|Object: Block type name or its metadata.Object: Block settings.Returns
WPBlockType | undefined: The block, if it has been successfully registered; otherwise undefined.Registers a new block variation for the given block type.
For more information on block variations see the official documentation .
Usage
import { __ } from '@wordpress/i18n';
import { registerBlockVariation } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
registerBlockVariation( 'core/embed', {
name: 'custom',
title: __( 'My Custom Embed' ),
attributes: { providerNameSlug: 'custom' },
} );
} }
>
__( 'Add a custom variation for core/embed' ) }
</Button>
);
};
Parameters
string: Name of the block (example: “core/columns”).WPBlockVariation: Object describing a block variation.Takes a block or set of blocks and returns the serialized post content.
Parameters
Array: Block(s) to serialize.WPBlockSerializationOptions: Serialization options.Returns
string: The post content.Serializes a block node into the native HTML-comment-powered block format. CAVEAT: This function is intended for re-serializing blocks as parsed by valid parsers and skips any validation steps. This is NOT a generic serialization function for in-memory blocks. For most purposes, see the following functions available in the @wordpress/blocks package:
Related
@wordpress/block-serialization-default-parser package@wordpress/block-serialization-spec-parser packageParameters
WPRawBlock: A block node as returned by a valid parser.[Options]: Serialization options.Returns
string: An HTML string representing a block.Sets the block categories.
Usage
import { __ } from '@wordpress/i18n';
import { store as blocksStore, setCategories } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
// Retrieve the list of current categories.
const blockCategories = useSelect(
( select ) => select( blocksStore ).getCategories(),
[]
);
return (
<Button
onClick={ () => {
// Add a custom category to the existing list.
setCategories( [
...blockCategories,
{ title: 'Custom Category', slug: 'custom-category' },
] );
} }
>
{ __( 'Add a new custom block category' ) }
</Button>
);
};
Parameters
WPBlockCategory[]: Block categories.Assigns the default block name.
Usage
import { setDefaultBlockName } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button onClick={ () => setDefaultBlockName( 'core/heading' ) }>
{ __( 'Set the default block to Heading' ) }
</Button>
);
};
Parameters
string: Block name.Assigns name of block for handling non-block content.
Parameters
string: Block name.Assigns name of block for handling block grouping interactions.
This function lets you select a different block to group other blocks in instead of the default core/group block. This function must be used in a component or when the DOM is fully loaded. See https://developer.wordpress.org/block-editor/reference-guides/packages/packages-dom-ready/
Usage
import { setGroupingBlockName } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button onClick={ () => setGroupingBlockName( 'core/columns' ) }>
{ __( 'Wrap in columns' ) }
</Button>
);
};
Parameters
string: Block name.Assigns name of block handling unregistered block types.
Parameters
string: Block name.Store definition for the blocks namespace.
Related
Type
ObjectSwitch one or more blocks into one or more blocks of the new block type.
Parameters
Array|Object: Blocks array or block object.string: Block name.Returns
?Array: Array of blocks or null.Synchronize a block list with a block template.
Synchronizing a block list with a block template means that we loop over the blocks keep the block as is if it matches the block at the same position in the template (If it has the same name) and if doesn't match, we create a new block based on the template. Extra blocks not present in the template are removed.
Parameters
Array: Block list.Array: Block template.Returns
Array: Updated Block list.Unregisters a block bindings source by providing its name.
Usage
import { unregisterBlockBindingsSource } from '@wordpress/blocks';
unregisterBlockBindingsSource( 'plugin/my-custom-source' );
Parameters
string: The name of the block bindings source to unregister.Changelog
6.7.0 Introduced in WordPress core.
Unregisters a block style for the given block.
Usage
import { __ } from '@wordpress/i18n';
import { unregisterBlockStyle } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
unregisterBlockStyle( 'core/quote', 'plain' );
} }
>
{ __( 'Remove the "Plain" block style for core/quote' ) }
</Button>
);
};
Parameters
string: Name of block (example: “core/latest-posts”).string: Name of class applied to the block.Unregisters a block.
Usage
import { __ } from '@wordpress/i18n';
import { unregisterBlockType } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button
onClick={ () => unregisterBlockType( 'my-collection/block-name' ) }
>
{ __( 'Unregister my custom block.' ) }
</Button>
);
};
Parameters
string: Block name.Returns
WPBlockType | undefined: The previous block value, if it has been successfully unregistered; otherwise undefined.Unregisters a block variation defined for the given block type.
Usage
import { __ } from '@wordpress/i18n';
import { unregisterBlockVariation } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
unregisterBlockVariation( 'core/embed', 'youtube' );
} }
>
{ __( 'Remove the YouTube variation from core/embed' ) }
</Button>
);
};
Parameters
string: Name of the block (example: “core/columns”).string: Name of the variation defined for the block.Updates a category.
Usage
import { __ } from '@wordpress/i18n';
import { updateCategory } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
updateCategory( 'text', { title: __( 'Written Word' ) } );
} }
>
{ __( 'Update Text category title' ) }
</Button>
);
};
Parameters
string: Block category slug.WPBlockCategory: Object containing the category properties that should be updated.Returns an object with isValid property set to true if the parsed block is valid given the input content. A block is considered valid if, when serialized with assumed attributes, the content matches the original value. If block is invalid, this function returns all validations issues as well.
Parameters
WPBlock: block object.[WPBlockType|string]: Block type or name, inferred from block if not given.Returns
[boolean,Array<LoggerItem>]: validation results.Deprecated
A Higher Order Component used to inject BlockContent using context to the wrapped component.
Parameters
Component: The component to enhance.Returns
Component: The same component.This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main contributor guide.

FAQs
Block API for WordPress.
We found that @wordpress/blocks demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 23 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
GitHub postponed a new billing model for self-hosted Actions after developer pushback, but moved forward with hosted runner price cuts on January 1.

Research
Destructive malware is rising across open source registries, using delays and kill switches to wipe code, break builds, and disrupt CI/CD.

Security News
Socket CTO Ahmad Nassri shares practical AI coding techniques, tools, and team workflows, plus what still feels noisy and why shipping remains human-led.