WP_Block_Processor::next_block( string|null $block_type = null ): bool

Advance to the next block delimiter which opens a block, indicating if one was found.

Description

Delimiters which open blocks include opening and void block delimiters. To visit freeform HTML content, pass the wildcard “*” as the block type.

Use this function to walk through the blocks in a document, pausing where they open.

Example blocks:

// The first delimiter opens the paragraph block.
<⃨!⃨-⃨-⃨ ⃨w⃨p⃨:⃨p⃨a⃨r⃨a⃨g⃨r⃨a⃨p⃨h⃨ ⃨-⃨-⃨>⃨<p>Content</p><!-- /wp:paragraph-->

// The void block is the first opener in this sequence of closers.
<!-- /wp:group --><⃨!⃨-⃨-⃨ ⃨w⃨p⃨:⃨s⃨p⃨a⃨c⃨e⃨r⃨ ⃨{⃨"⃨h⃨e⃨i⃨g⃨h⃨t⃨"⃨:⃨"⃨2⃨0⃨0⃨p⃨x⃨"⃨}⃨ ⃨/⃨-⃨-⃨>⃨<!-- /wp:group -->

// If, however, `*` is provided as the block type, freeform content is matched.
<⃨h⃨2⃨>⃨M⃨y⃨ ⃨s⃨y⃨n⃨o⃨p⃨s⃨i⃨s⃨<⃨/⃨h⃨2⃨>⃨\⃨n⃨<!-- wp:my/table-of-contents /-->

// Inner HTML is never freeform content, and will not be matched even with the wildcard.
<!-- /wp:list-item --></ul><!-- /wp:list --><⃨!⃨-⃨-⃨ ⃨w⃨p⃨:⃨p⃨a⃨r⃨a⃨g⃨r⃨a⃨p⃨h⃨ ⃨-⃨>⃨<p>

Example:

// Find all textual ranges of image block opening delimiters.
$images = array();
$processor = new WP_Block_Processor( $html );
while ( $processor->next_block( 'core/image' ) ) {
    $images[] = $processor->get_span();
}

In some cases it may be useful to conditionally visit the implicit freeform blocks, such as when determining if a post contains freeform content that isn’t purely whitespace.

Example:

 $seen_block_types = [];
 $block_type       = '*';
 $processor        = new WP_Block_Processor( $html );
 while ( $processor->next_block( $block_type ) {
     // Stop wasting time visiting freeform blocks after one has been found.
     if (
         '*' === $block_type &&
         null === $processor->get_block_type() &&
         $processor->is_non_whitespace_html()
     ) {
         $block_type = null;
         $seen_block_types['core/freeform'] = true;
         continue;
     }

     $seen_block_types[ $processor->get_block_type() ] = true;
 }

See also

Parameters

$block_typestring|nulloptional
If provided, advance until a block of this type is found.
Default is to stop at any block regardless of its type.

Default:null

Return

bool Whether an opening delimiter for a block was found.

Source

public function next_block( ?string $block_type = null ): bool {
	while ( $this->next_delimiter( $block_type ) ) {
		if ( self::CLOSER !== $this->get_delimiter_type() ) {
			return true;
		}
	}

	return false;
}

Changelog

VersionDescription
6.9.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.