Skip to main content

@wordpress/blocks

The @wordpress/blocks package provides the foundational Block API for WordPress. It handles block registration, parsing, serialization, and transformations.

Installation

npm install @wordpress/blocks --save
Current Version: 15.13.0This package assumes an ES2015+ environment. Include the polyfill from @wordpress/babel-preset-default if needed.

What are Blocks?

Blocks are the abstract units of markup that compose the content or layout of a webpage. They combine concepts previously achieved with shortcodes, custom HTML, and embed discovery into a single consistent API.

Core Concepts

Block Registration

Register a new block type with registerBlockType:
import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';

registerBlockType( 'namespace/block-name', {
  title: __( 'My First Block' ),
  edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
  save: () => <div>Hello from the saved content!</div>,
} );
blockNameOrMetadata
string | Object
required
Block type name (e.g., ‘namespace/block-name’) or block metadata object
settings
Object
required
Block settings object with the following properties:
  • title: Human-readable block name
  • edit: React component for the editor
  • save: Function returning the saved output
  • attributes: Block attribute schema
  • category: Block category for the inserter
return
WPBlockType | undefined
The registered block if successful, otherwise undefined

Block Parsing

Parse post content into blocks:
import { parse } from '@wordpress/blocks';

const blocks = parse( '<!-- wp:paragraph --><p>Hello World</p><!-- /wp:paragraph -->' );
console.log( blocks );
// [
//   {
//     name: 'core/paragraph',
//     attributes: { content: 'Hello World' },
//     innerBlocks: []
//   }
// ]
content
string
required
The post content to parse (HTML with block comments)
options
ParseOptions
Extra options for handling block parsing
return
Array
Array of block objects with name, attributes, and innerBlocks

Block Serialization

Serialize blocks back to post content:
import { serialize, createBlock } from '@wordpress/blocks';

const block = createBlock( 'core/paragraph', {
  content: 'Hello World'
} );

const postContent = serialize( [ block ] );
// "<!-- wp:paragraph -->\n<p>Hello World</p>\n<!-- /wp:paragraph -->"
blocks
Array
required
Block or array of blocks to serialize
options
WPBlockSerializationOptions
Serialization options
return
string
The serialized post content

API Reference

Block Creation

import { createBlock } from '@wordpress/blocks';

const block = createBlock(
  'core/paragraph',
  { content: 'Hello World' },
  [] // innerBlocks
);

createBlock

Returns a block object given its type and attributes.
name
string
required
Block name (e.g., ‘core/paragraph’)
attributes
Object
Block attributes
innerBlocks
Array
Nested blocks
return
Object
Block object with name, attributes, innerBlocks, and clientId

cloneBlock

Given a block object, returns a copy with optional merged attributes and/or replaced inner blocks.
block
Object
required
Block instance to clone
mergeAttributes
Object
Attributes to merge with the cloned block
newInnerBlocks
Array
Inner blocks to replace in the clone
return
Object
A cloned block with merged attributes

Block Types

registerBlockType

Registers a new block provided a unique name and an object defining its behavior.
import { registerBlockType } from '@wordpress/blocks';

registerBlockType( 'namespace/block-name', {
  title: 'My First Block',
  icon: 'smiley',
  category: 'text',
  attributes: {
    content: {
      type: 'string',
      source: 'html',
      selector: 'p',
    }
  },
  edit: ( { attributes, setAttributes } ) => {
    return (
      <p>
        { attributes.content }
      </p>
    );
  },
  save: ( { attributes } ) => {
    return <p>{ attributes.content }</p>;
  },
} );
See the Create a Block tutorial for comprehensive block registration guidance.

getBlockType

Returns a registered block type.
import { getBlockType } from '@wordpress/blocks';

const blockType = getBlockType( 'core/paragraph' );
console.log( blockType.title ); // "Paragraph"
name
string
required
Block name
return
Object | null
Block type object or null if not found

getBlockTypes

Returns all registered blocks.
import { getBlockTypes } from '@wordpress/blocks';

const allBlocks = getBlockTypes();
console.log( allBlocks.length );
return
Array
Array of all registered block settings

unregisterBlockType

Unregisters a block.
import { unregisterBlockType } from '@wordpress/blocks';

unregisterBlockType( 'my-plugin/custom-block' );
name
string
required
Block name
return
WPBlockType | undefined
The previous block value if successfully unregistered

Block Variations

registerBlockVariation

Registers a new block variation for a given block type.
import { registerBlockVariation } from '@wordpress/blocks';

registerBlockVariation( 'core/embed', {
  name: 'youtube',
  title: 'YouTube',
  attributes: { providerNameSlug: 'youtube' },
} );
blockName
string
required
Name of the block (e.g., ‘core/columns’)
variation
WPBlockVariation
required
Object describing the block variation:
  • name: Unique variation name
  • title: Human-readable variation title
  • attributes: Default attributes for the variation
  • icon: Optional icon
  • scope: Where the variation appears (inserter, block, transform)
See the Block Variations documentation for more details.

unregisterBlockVariation

Unregisters a block variation defined for a given block type.
import { unregisterBlockVariation } from '@wordpress/blocks';

unregisterBlockVariation( 'core/embed', 'youtube' );
blockName
string
required
Name of the block
variationName
string
required
Name of the variation to unregister

Block Styles

registerBlockStyle

Registers a new block style for given block types.
import { registerBlockStyle } from '@wordpress/blocks';

registerBlockStyle( 'core/quote', {
  name: 'fancy-quote',
  label: 'Fancy Quote',
} );
blockNames
string | Array
required
Name of block(s) or array of block names (e.g., ‘core/quote’ or [‘core/group’, ‘core/columns’])
styleVariation
Object
required
Style variation object:
  • name: CSS class name applied to the block
  • label: Human-readable label shown to users
See the Block Styles documentation for styling guidance.

unregisterBlockStyle

Unregisters a block style for a given block.
import { unregisterBlockStyle } from '@wordpress/blocks';

unregisterBlockStyle( 'core/quote', 'plain' );
blockName
string
required
Name of the block
styleVariationName
string
required
Name of the style to unregister

Block Categories

setCategories

Sets the block categories.
import { setCategories } from '@wordpress/blocks';
import { store as blocksStore } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';

const blockCategories = useSelect(
  ( select ) => select( blocksStore ).getCategories(),
  []
);

setCategories( [
  ...blockCategories,
  { title: 'Custom Category', slug: 'custom-category' },
] );
categories
WPBlockCategory[]
required
Array of category objects with title and slug properties

updateCategory

Updates a category.
import { updateCategory } from '@wordpress/blocks';

updateCategory( 'text', { title: 'Written Word' } );
slug
string
required
Block category slug
category
WPBlockCategory
required
Object with properties to update (e.g., title)

Block Collections

registerBlockCollection

Registers a new block collection to group blocks in the same namespace.
import { registerBlockCollection, registerBlockType } from '@wordpress/blocks';

registerBlockCollection( 'my-plugin', {
  title: 'My Plugin Blocks',
  icon: 'smiley',
} );

registerBlockType( 'my-plugin/custom-block', {
  title: 'Custom Block',
  // ... other settings
} );
namespace
string
required
The namespace to group blocks (corresponds to block namespace)
settings
Object
required
Collection settings:
  • title: Display title in block inserter
  • icon: Optional icon to display

Block Transformations

switchToBlockType

Switch one or more blocks into blocks of a new block type.
import { switchToBlockType } from '@wordpress/blocks';

const newBlocks = switchToBlockType( blocks, 'core/group' );
blocks
Array | Object
required
Block(s) to transform
name
string
required
Target block name
return
Array | null
Array of transformed blocks or null if transformation failed

getBlockTransforms

Returns normal block transforms for a given direction.
import { getBlockTransforms } from '@wordpress/blocks';

const transforms = getBlockTransforms( 'to', 'core/paragraph' );
direction
string
required
Transform direction: ‘to’ or ‘from’
blockTypeOrName
string | Object
Optional block type or name to filter transforms
return
Array
Array of block transforms for the direction

getPossibleBlockTransformations

Returns block types that the given blocks can be transformed into.
import { getPossibleBlockTransformations } from '@wordpress/blocks';

const possibleTypes = getPossibleBlockTransformations( blocks );
blocks
Array
required
Array of blocks
return
Array
Block types that the blocks can be transformed to

Block Validation

validateBlock

Returns validation results for a parsed block.
import { validateBlock } from '@wordpress/blocks';

const [ isValid, issues ] = validateBlock( block );
if ( ! isValid ) {
  console.error( 'Validation issues:', issues );
}
block
WPBlock
required
Block object to validate
blockTypeOrName
WPBlockType | string
Block type or name (inferred from block if not provided)
return
[boolean, Array<LoggerItem>]
Tuple with validation status and array of validation issues

Block Support

hasBlockSupport

Returns true if the block defines support for a feature.
import { hasBlockSupport } from '@wordpress/blocks';

const supportsAlign = hasBlockSupport( 'core/paragraph', 'align', false );
nameOrType
string | Object
required
Block name or type object
feature
string
required
Feature to test (e.g., ‘align’, ‘html’, ‘anchor’)
defaultSupports
boolean
Default value if feature support is not explicitly defined
return
boolean
Whether the block supports the feature

getBlockSupport

Returns the block support value for a feature.
import { getBlockSupport } from '@wordpress/blocks';

const alignSupport = getBlockSupport( 'core/paragraph', 'align' );
nameOrType
string | Object
required
Block name or type object
feature
string
required
Feature to retrieve
defaultSupports
*
Default value to return if not explicitly defined
return
* | null
Block support value

Block Bindings

registerBlockBindingsSource

Registers a new block bindings source.
import { registerBlockBindingsSource } from '@wordpress/blocks';
import { _x } from '@wordpress/i18n';

registerBlockBindingsSource( {
  name: 'plugin/my-custom-source',
  label: _x( 'My Custom Source', 'block bindings source' ),
  usesContext: [ 'postType' ],
  getValues: ( { bindings, context } ) => {
    // Return values for bound attributes
  },
  setValues: ( { bindings, context, values } ) => {
    // Update values
  },
  canUserEditValue: () => true,
} );
source
WPBlockBindingsSource
required
Block bindings source configuration:
  • name: Unique source identifier
  • label: Human-readable label
  • usesContext: Optional array of context values needed
  • getValues: Function to retrieve bound values
  • setValues: Optional function to update values
  • canUserEditValue: Optional function to check edit permissions
Introduced in WordPress 6.7.0

getBlockBindingsSource

Returns a registered block bindings source by name.
import { getBlockBindingsSource } from '@wordpress/blocks';

const source = getBlockBindingsSource( 'core/post-meta' );
name
string
required
Block bindings source name
return
Object | null
Block bindings source or null

unregisterBlockBindingsSource

Unregisters a block bindings source.
import { unregisterBlockBindingsSource } from '@wordpress/blocks';

unregisterBlockBindingsSource( 'plugin/my-custom-source' );
name
string
required
Block bindings source name to unregister

Utility Functions

getBlockDefaultClassName

Returns the block’s default classname from its name.
import { getBlockDefaultClassName } from '@wordpress/blocks';

const className = getBlockDefaultClassName( 'core/paragraph' );
// "wp-block-paragraph"

pasteHandler

Converts HTML string to blocks, stripping everything else.
import { pasteHandler } from '@wordpress/blocks';

const blocks = pasteHandler( {
  HTML: '<p>Pasted content</p>',
  mode: 'BLOCKS',
} );
options.HTML
string
The HTML to convert
options.plainText
string
Plain text version
options.mode
string
Handle content as blocks or inline:
  • AUTO: Decide based on content
  • INLINE: Always handle as inline, return string
  • BLOCKS: Always handle as blocks, return array
return
Array | string
List of blocks or string depending on mode

Default Blocks

setDefaultBlockName

Assigns the default block name.
import { setDefaultBlockName } from '@wordpress/blocks';

setDefaultBlockName( 'core/paragraph' );
name
string
required
Block name to set as default

getDefaultBlockName

Retrieves the default block name.
import { getDefaultBlockName } from '@wordpress/blocks';

const defaultBlock = getDefaultBlockName();
// "core/paragraph"
return
string | null
Default block name

setFreeformContentHandlerName

Assigns the block name for handling non-block content.
import { setFreeformContentHandlerName } from '@wordpress/blocks';

setFreeformContentHandlerName( 'core/html' );
blockName
string
required
Block name for freeform content

Store

The blocks package includes a data store:
import { store as blocksStore } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';

function MyComponent() {
  const blockTypes = useSelect( ( select ) => {
    return select( blocksStore ).getBlockTypes();
  }, [] );
  
  return <div>{ blockTypes.length } blocks registered</div>;
}
store
Object
Store definition for the blocks namespace. See @wordpress/data for details.

TypeScript

Type definitions are available:
import type { WPBlockType, WPBlock, BlockInstance } from '@wordpress/blocks';

const block: BlockInstance = createBlock( 'core/paragraph', {
  content: 'Hello',
} );

Dependencies

The package depends on:
  • @wordpress/data - State management
  • @wordpress/element - React abstraction
  • @wordpress/i18n - Internationalization
  • @wordpress/hooks - Plugin API
  • @wordpress/rich-text - Rich text formatting
  • @wordpress/dom - DOM utilities
  • And several utility packages
See package.json for the complete dependency list.

Resources

Create a Block Tutorial

Learn how to create your first block

Block API Reference

Complete block API documentation

GitHub Repository

Source code and issue tracker

What Are Blocks?

Design principles behind blocks

Build docs developers (and LLMs) love