Search by

n5s / wp-block-visitor

n5s

There is no license information available for the latest version (0.x-dev) of this package.

A powerful WordPress library to extract data from blocks or tranform blocks effortlessly.

Package info

github.com/nlemoine/wp-block-visitor

pkg:composer/n5s/wp-block-visitor

Statistics

Installs: 7 549

Dependents: 1

Suggesters: 0

Stars: 2

Open Issues: 0

0.x-dev 2026-12-03 11:26 UTC

This package is auto-updated.

Last update: 2026-12-03 11:40:13 UTC


README

Traverse and transform WordPress block trees with visitors. Parse post content once, walk every block depth-first, extract data or rewrite blocks in place, then serialize back to block markup. Untouched blocks are written back the way serialize_blocks() writes them, so a no-op traversal leaves content saved by the editor unchanged.

Warning

🚧 Work in progress. The API may change without notice.

Install

composer require n5s/wp-block-visitor

Requires PHP 8.3+ and WordPress 6.5+, loaded: the block functions (parse_blocks, serialize_block_attributes) and the HTML API (WP_HTML_Tag_Processor, with the token methods added in 6.5). The tests run against the latest WordPress only.

Usage

use n5s\BlockVisitor\BlockNode;
use n5s\BlockVisitor\BlockTraverser;
use n5s\BlockVisitor\Visitor\AbstractBlockVisitor;
use n5s\BlockVisitor\Visitor\Traversal;

final class RenameButtonVisitor extends AbstractBlockVisitor
{
    public function leave(BlockNode $block): BlockNode|array|Traversal|null
    {
        if ($block->getBlockName() === 'vendor/button') {
            $block->setBlockName('core/button')->renameAttribute('href', 'url');
        }

        return null;
    }
}

$traverser = new BlockTraverser(new RenameButtonVisitor());
$root = $traverser->traverse($post->post_content);

$post->post_content = (string) $root;

traverse() accepts the markup of a document, or a root built by BlockNode::createRoot(), and returns the root node. Cast it to a string to get the serialized markup back.

The node a traversal starts from is never visited itself, so traverse() refuses a node that is not a root (InvalidArgumentException). To visit blocks built by hand, make them a document first: $traverser->traverse(BlockNode::createRoot([$block])). To visit only the inner blocks of a node, from a hook for instance, call $traverser->traverseChildren($node).

Visitors

A visitor implements BlockVisitorInterface, or extends AbstractBlockVisitor and overrides the hook it needs. Nodes are visited depth-first in document order: enter() is called before the children of a node, leave() after them. The root node is never visited.

interface BlockVisitorInterface
{
    public function beforeTraverse(BlockNode $root): void;

    public function afterTraverse(BlockNode $root): void;

    public function enter(BlockNode $block): BlockNode|Traversal|null;

    public function leave(BlockNode $block): BlockNode|array|Traversal|null;
}

Return null to do nothing. This is the default for both node hooks in AbstractBlockVisitor, so a read-only visitor only overrides enter() and never returns anything else.

beforeTraverse() and afterTraverse() are called once per pass with the root, before the first node and after the last one. afterTraverse() also runs after Traversal::Stop, not after an exception. They are the place to reset or flush state a visitor keeps across documents; AbstractBlockVisitor implements both as no-ops. The top-level blocks are not locked in either, so this is also where a visitor adds or removes one directly on the root.

Mutation rules

Which mutation goes where is the whole point of the library, so here are the rules.

The current node and its subtree are mutated in place through the BlockNode API, without returning anything: attributes, content, children. Children added in enter() are visited afterwards; children added in leave() are not.

The current node itself is replaced, removed, expanded or wrapped through the return value of leave():

Return from leave() Effect
null nothing
a BlockNode replaces the node
a list of BlockNode replaces the node by zero or more siblings, e.g. [$block, $newSibling] inserts a sibling after it
Traversal::Remove removes the node
Traversal::Stop stops the traversal for this visitor

Nodes returned from leave() are not visited again by the same visitor, so wrapping a block in a new parent never loops:

public function leave(BlockNode $block): BlockNode|array|Traversal|null
{
    if ($block->getBlockName() !== 'core/paragraph') {
        return null;
    }

    return BlockNode::wrap($block, 'core/group', [], "\n<div class=\"wp-block-group\">", "</div>\n");
}

wrap() is for the node being left. From a hook, the wrapped node keeps its place and its parent until the traverser swaps the wrapper in from what leave() returned. A wrapper built around any other node, or built and not returned, can be used nowhere: every mutator rejects a node that holds a block still listed elsewhere, and the wrapper itself refuses that block a second time. It can still take other blocks before it is returned. The node being left comes back once: a list that returns it both as itself and inside a wrapper, or inside two wrappers, is rejected, return a clone for the others. Outside a visitor, wrap() puts the wrapper in the child's place itself.

enter() can return a BlockNode to replace the current node before its children are visited, Traversal::SkipChildren to skip the subtree (leave() is still called), or Traversal::Stop. It cannot remove: Traversal::Remove there throws a LogicException. Nor can it expand: a list is not a value enter() may return, so PHP raises a TypeError. The children of a node returned from enter() are visited, so that node cannot hold the current one: returning BlockNode::wrap($block, ...) there would visit $block again and wrap it forever, and the traverser throws a LogicException instead. Wrap from leave(). A new node holding a copy of the current one is not caught that way and nests without end: the traversal stops with a LogicException once it is BlockNode::MAX_DEPTH levels deep.

Traversal::Stop ends the pass at once: leave() is not called for the nodes still open, and the values already returned for the lists being visited are applied. The visitors registered after it still get their pass.

Ancestors and siblings are never mutated from a visitor. While a node's children are visited, the traverser locks its children list: any call that would change it, including attaching one of those children somewhere else, throws a LogicException right where the visitor makes it, before anything changes. That covers removals, insertions, swaps and reorderings anywhere in the list, from the current node's hooks or from its descendants'. Changing the attributes or the content of an ancestor does not touch its children and is not rejected. Neither is a change made inside a sibling, which the lock does not watch: a sibling still to visit is then visited as changed, one already visited is not visited again, so do not rely on it. To act on a parent based on what a child contains, record the fact in the visitor state during the child's visit and act in leave() of the parent.

A leave() return value is applied once the whole sibling list has been visited, so later siblings still observe the node it replaces. All the values returned for one sibling list are applied in a single pass, so removing every child of a wide parent stays linear. Attaching a block somewhere takes it away from its former parent. Nodes attached in one call leave each former parent in one pass, so moving or unwrapping many children at once stays linear too; moved one call at a time, each costs a search of its former list. A block can never be added under itself or under one of its own descendants.

Exceptions thrown by a visitor propagate unchanged. That is the way to abort the traversal of a document with an error. The tree is then in an undefined state: replacements staged by earlier siblings are not applied, so discard it rather than serializing it. Every exception the library itself throws implements n5s\BlockVisitor\Exception\ExceptionInterface and extends the SPL class of the same name (LogicException, InvalidArgumentException, OutOfRangeException, RuntimeException), so a catch can tell a contract violation from your own abort.

Returning a node that is the current node's parent or one of its ancestors is rejected too, since it would create a cycle. So is returning a sibling of the current node, from either hook: moving it would shift the siblings still to visit. A list returned from leave() must only hold BlockNode instances.

Multiple visitors

Each visitor gets its own full pass over the tree, so a visitor sees the result of the previous ones. Visitors run in registration order, unless they implement PrioritizedVisitorInterface: higher priority runs first.

$traverser = new BlockTraverser($cleanupVisitor, $galleryVisitor, $treeVisitor);

BlockNode

Factories

BlockNode::create($parsedBlock);                          // from a parse_blocks() array
BlockNode::createFromString('<!-- wp:paragraph -->...');  // markup holding exactly one block
BlockNode::createRoot($postContent);                      // root holding every top-level block
BlockNode::createRoot([$block, $parsedBlockArray]);       // root made of blocks built by hand
BlockNode::wrap($child, 'core/group', $attrs, $before, $after); // takes $child's place in its parent; from leave(), the traverser makes the swap
new BlockNode('core/group', $attrs, $children, $innerContent);  // children that have a parent are moved here

The n5s\BlockVisitor\Internal namespace only serves BlockNode; it is not part of the supported API and can change in any release. Neither are BlockNode::lockChildren(), unlockChildren() and applyReplacements(), marked @internal: they are how the traverser holds the traversal lock and applies what leave() returned.

Reading

$block->getBlockName();
$block->getAttributes();
$block->getAttribute('className');
$block->hasAttribute('id');
$block->getClassNames();
$block->hasClassName('is-style-outline');
$block->getInnerBlocks();
$block->getInnerContent();      // HTML chunks, null marks the position of a child
$block->getInnerHTML();         // the HTML chunks of innerContent joined, as the parser builds it
$block->getParent();
$block->getDepth();             // top-level blocks are at depth 0
$block->isRoot();
$block->isFreeform();           // HTML outside of any block: no name, no delimiters
$block->indexOf($child);

Attributes

$block->setBlockName('core/paragraph');
$block->setAttribute('id', 'intro');
$block->setAttributes(['id' => 'intro']);
$block->removeAttribute('id');
$block->removeAttributes(['id', 'anchor']);
$block->renameAttribute('anchorId', 'anchor');
$block->clearAttributes();
$block->addClassName('is-style-outline');
$block->removeClassName('is-style-fill');

The class helpers read and write the className attribute, split on whitespace like an HTML class: a name holding spaces is that many classes, and an empty one is none. They do not touch the markup. A static block whose saved HTML carries its classes needs that HTML changed as well, or the editor reports the block as invalid.

Children

Every child mutator keeps innerContent in sync: the HTML around the children is preserved, one placeholder per child is maintained, and parents are updated. A block appears at most once in the tree: inserting a node that is already a child of the same parent moves it, and listing the same node twice throws a LogicException. A root node cannot become a child: insert its inner blocks instead. A freeform node, the one without a name the parser builds for the text between blocks, cannot hold blocks: it has no delimiters to hold them in.

A node without children has no placeholder to tell where its first blocks go. The child mutators decide from its content, by the first rule that applies:

  1. Content split in two or more chunks: before the last chunk.
  2. A single chunk holding an empty div: inside the last one. That is the element a cover, a media-text or a legacy group keeps for its blocks.
  3. A single chunk with a closing tag: before the last closing tag, so inside <div class="wp-block-group"></div>, and after the text of <li>Item</li>, where a nested list goes.
  4. Anything else, no content included: after the content.

These rules decide what is written, and two kinds of markup defeat them. A quote's citation and a gallery's caption come after the inner blocks, which no rule on the closing tags can know: the first block inserted into an empty quote or gallery that has one lands after it. A node whose only markup is an element holding text, such as <p>Intro</p>, gets its first block inside that element. In both cases say where the blocks go before inserting them, with the content split there, which is rule 1:

$quote->setInnerContent(['<blockquote class="wp-block-quote">', '<cite>Author</cite></blockquote>']);
$quote->appendInnerBlock($paragraph); // between the two chunks

Only the child mutators cut a chunk. The constructor, create() and setInnerContent() take the content as it is given and add the placeholders it lacks after it, so a container built with its children in one call needs its content as a list, placeholders included.

$block->appendInnerBlock($child);
$block->appendInnerBlocks([$child, $parsedBlockArray]);
$block->prependInnerBlock($child);
$block->prependInnerBlocks([$child, $parsedBlockArray]);
$block->insertInnerBlockAt(1, $child);
$block->replaceInnerBlockAt(1, $a, $b);   // zero nodes removes, one replaces, more expand
$block->removeInnerBlockAt(1);
$block->removeInnerBlock($child);        // by identity; refuses a node that is not a child
$block->setInnerBlocks([$a, $b]);        // same count: content untouched; otherwise keeps the HTML before the first child and after the last one

clone $block copies the whole subtree: the children are copies too, and the copy has no parent until it is inserted somewhere, so changing it never touches the original. Attribute values are copied as PHP copies arrays, so an object stored as an attribute value stays shared; the parser never produces one. serialize($block) follows the same rule: it writes the subtree without its parent, so one block does not take the whole document along, and unserialize() gives back a node without a parent. A payload is checked like the arguments of the constructor: one that lists a node in two places, or inside itself, is refused.

New siblings are joined with the separator the list already uses between its first two children: the same whitespace chunk, nothing when they are adjacent, and a blank line (\n\n) when the list has fewer than two children or markup between them. At the top level there is never one: WordPress keeps the blank lines between top-level blocks as freeform blocks, so a new top-level block is written right after the previous one, as serialize_blocks() does, and a reparse gives back the same blocks.

Content

$block->setInnerContent('<p>Hello</p>');                  // single chunk, placeholders appended after it
$block->setInnerContent(["\n<div>", null, "</div>\n"]);  // full chunk list
$block->wrapInnerContent('<div class="wp-block-group">', '</div>'); // written as given on each side, nothing is read from the markup
$block->clearInnerContent();                              // drops the HTML, keeps the placeholders

Rejected input

Block names must look like paragraph, core/paragraph or my_plugin/my_block, the same names the WordPress parser reads; any other name raises InvalidArgumentException. A name without a namespace is stored the way the parser reads it back, so (new BlockNode('paragraph'))->getBlockName() is core/paragraph and a visitor matching core/paragraph finds the node. @root is not a block name: it is what getBlockName() gives for a root, which only createRoot() builds. Given to the constructor, create(), wrap() or setBlockName(), or found in a parsed array, it raises InvalidArgumentException. A root cannot be renamed and can never become a child of another node (LogicException). createFromString() raises InvalidArgumentException for markup that is blank or holds more than one block, text around a block included. A parsed array whose keys do not have the types parse_blocks() gives them, or that nests blocks deeper than BlockNode::MAX_DEPTH (1000 levels), raises InvalidArgumentException: past a few thousand levels PHP crashes on the recursion instead of throwing, and no editor writes such a document. Parsed arrays are checked before any node they hold is moved, so a rejected call leaves every node where it was. Attribute values must be JSON-encodable, or serialization raises RuntimeException. Attributes shaped as a list, which is how the parser reads {"0":"a"}, are written back as a JSON object, so the delimiter still reparses as the same block. Each of those rules exists because the alternative is a delimiter that WordPress reparses as something else, swallowing the blocks that follow.

Serialization

(string) $block;    // block markup, or the whole document for a root node
$block->toArray();  // parse_blocks() shape

A root is a document, not a block, so toArray() throws a LogicException on it. The parse_blocks() equivalent of the document is the array of each top-level block: array_map(fn (BlockNode $block) => $block->toArray(), $root->getInnerBlocks()). One difference with the parser: attributes it could not read, which it gives as null, come back as an empty array. And one with serialize_blocks(): attributes whose keys are all numeric and in order stay a JSON object ({"0":"a"}), where WordPress writes a list (["a"]) and its own parser then no longer reads the block.

Examples

Migrate a block to another

examples/AccordionToDetailsVisitor.php replaces a third-party accordion with core details blocks: each acme/accordion-item becomes a core/details that keeps its inner blocks, and the acme/accordion around them is unwrapped. It shows the moves a migration usually needs: renaming a block, converting its attributes, rewriting its own markup around untouched children, unwrapping a parent from leave(), and passing a fact from a parent to its children through the visitor state (an exclusive accordion becomes a shared name on its details).

The target block decides where each value goes. core/details reads its summary and its name from the HTML, not from the delimiter, so the migration writes them into the markup and keeps only showContent as an attribute. Check the target's block.json: an attribute with a source must be in the markup, and a value left in the delimiter instead is ignored.

Running it over every post:

$traverser = new BlockTraverser(new AccordionToDetailsVisitor());

$types = ['post', 'page', 'wp_block', 'wp_template', 'wp_template_part'];

foreach (get_posts(['post_type' => $types, 'post_status' => 'any', 's' => 'wp:acme/accordion', 'numberposts' => -1, 'fields' => 'ids']) as $id) {
    $before = get_post_field('post_content', $id, 'raw');
    $after = (string) $traverser->traverse($before);

    if ($after !== $before) {
        wp_update_post(wp_slash(['ID' => $id, 'post_content' => $after]));
    }
}
  • List the post types yourself: 'any' skips the ones excluded from search, synced patterns (wp_block) and templates included, and blocks live there too.
  • wp_update_post() unslashes its input, and serialized attributes escape characters such as < or & as \u003c or \u0026: without wp_slash() the backslashes are stripped and the values come back as u003c.
  • On save, the content goes through kses unless the current user has unfiltered_html. From WP-CLI, there is no user by default: pass --user with an administrator (a super admin on multisite), or markup the editor allows can be stripped.
  • Untouched blocks come back byte for byte, so comparing the strings tells which posts changed. Run once without saving to review them, and keep the migration idempotent, as this one is, so a second run is a no-op.
  • For post types that support revisions, wp_update_post() stores one, so a migrated post can be restored from the editor.

Prime the attachment cache for a list of posts

WordPress already primes the attachments of one post, but late and partially: wp_filter_content_tags() runs on the_content after do_blocks() and only sees <img> tags carrying a wp-image-{ID} class. Render callbacks that read the attachment before that, such as core/video or core/image with the lightbox enabled, still query it one by one, and nothing primes across posts. Collecting the IDs of a whole list of posts before the loop loads every attachment and its meta in two queries. The visitor is not shipped with the package: copy examples/AttachmentIdVisitor.php into your project under your own namespace.

$visitor = new AttachmentIdVisitor();
$traverser = new BlockTraverser($visitor);
foreach ($query->posts as $post) {
    $traverser->traverse($post->post_content);
}
$visitor->prime(); // _prime_post_caches() on every collected ID

For a single post, prime from the_content at priority 8 or lower so it runs before do_blocks() (priority 9). Later than that, the render callbacks have already queried their attachments.

The visitor knows the core media blocks and accepts a map of block names to ID attributes for custom blocks. The map replaces the core one, so spread AttachmentIdVisitor::CORE_ATTRIBUTES into it to keep both.

Runnable demos

examples/ contains runnable visitors, exposed as WP-CLI commands:

wp visitor tree --require=examples/cli.php     # print the block tree of a fixture
wp visitor depth --require=examples/cli.php    # print every block with its depth
wp visitor gallery --require=examples/cli.php  # expand a gallery into image blocks
wp visitor wrap --require=examples/cli.php     # wrap top-level paragraphs in groups
wp visitor remove --require=examples/cli.php   # remove every paragraph, print the tree
wp visitor ids --require=examples/cli.php      # collect the attachment IDs of a fixture
wp visitor migrate --require=examples/cli.php  # migrate an accordion to details blocks

Run the tests before (composer install && composer test) so a WordPress instance can be found.

Cost

Compared with parse_blocks() and WordPress 6.9's streaming WP_Block_Processor on a 2000-block document, PHP 8.5, Apple Silicon (composer bench):

2000 blocks BlockTraverser WP_Block_Processor parse_blocks()
Read: collect attachment IDs 15 ms, 15 MB 13 ms, 8 MB 10 ms, 14 MB
Write: add a class to every image 17 ms, 15 MB 17 ms, 9 MB 13 ms, 16 MB

Memory is the process peak, 7 MB of which is PHP itself. Of the 15 ms of the read, 8.4 ms are parse_blocks(), 2.8 ms build the tree and 2.2 ms visit its 3939 nodes, freeform whitespace blocks included.

What you pay: a block tree in memory, about the size of the parse_blocks() array, and, to read, about 10 percent more time than WP_Block_Processor and 45 percent more than parse_blocks(), for building the nodes and dispatching the visitor. To write, it costs the same as WP_Block_Processor and 35 percent more than parse_blocks(), since serializing straight from the nodes makes up for building them.

What you get: children can be inserted, removed, replaced or wrapped and innerContent stays consistent; untouched blocks come back as serialize_blocks() would write them; visitors compose in passes. WP_Block_Processor reads without building anything and is the right tool for scanning, but a modification is a span you splice into the source yourself. parse_blocks() gives you the tree and leaves the bookkeeping to you.

Development

composer qa          # phpcs, phpstan, rector (dry run), phpunit
composer cs:fix      # fix coding standard violations
composer rector:fix  # apply rector rules
composer infection   # mutation testing, run on PHP 8.4
composer bench       # phpbench comparison with WP_Block_Processor and parse_blocks()

Tests load a real WordPress install backed by SQLite, so parse_blocks() and friends are the genuine core functions.