Make WordPress Core

Opened 9 months ago

Closed 9 months ago

Last modified 8 months ago

#59327 closed enhancement (fixed)

Add optional callback argument to serialize_block(s)

Reported by: bernhard-reiter's profile Bernhard Reiter Owned by: bernhard-reiter's profile Bernhard Reiter
Milestone: 6.4 Priority: normal
Severity: normal Version:
Component: General Keywords:
Focuses: Cc:

Description

For some operations, we need to traverse the parsed block tree (before it is eventually serialized). In order to minimize the number of tree traversals (which is a potentially costly operation), it seems that adding a callback function argument to serialize_block() -- which inevitably has to traverse the entire tree anyway -- is a natural fit.

Examples where this will come in handy:

  • theme arg injection into a block template loaded from a file.
  • Automatic insertion of hooked blocks (see #59313).

Change History (2)

#1 @Bernhard Reiter
9 months ago

  • Resolution set to fixed
  • Status changed from assigned to closed

In 56557:

General: Add optional callback argument to serialize_block(s).

Allow passing a function callback to serialize_block(s) that is invoked on each node in the tree of parsed blocks as it is traversed for serialization.

A function argument was chosen for passing the callback function as it reflects a pattern familiar from other algorithms that apply a given callback function while traversing a data structure -- most notably PHP's own array_map().

Introducing a filter was considered as an alternative but ultimately dismissed. For a fairly low-level and general-purpose function such as serialize_block(), using a filter to pass the callback seemed risky, as it also requires removing that filter after usage in order to prevent the callback from being accidentally applied when serialize_block() is called in an entirely different context.

Introducing a separate function for applying a given operation during tree traversal (i.e. independently of serialization) was also considered but dismissed, as it would unnecessarily duplicate tree traversal.

Props dlh, gziolo.
Fixes #59327. See #59313.

#2 @Bernhard Reiter
8 months ago

In 56618:

Blocks: Implement block insertion functions.

For #59313, we need to implement functions to insert a given parsed block into another parsed block's inner blocks, and to prepend and append to that array, respectively.

We will use those functions in combination with traverse_and_serialize_blocks (see #59327) to implement automatic insertion of hooked blocks into block templates and patterns.

Props gziolo.
Fixes #59385.

Note: See TracTickets for help on using tickets.