WP_Block_Processor::opens_block( string[] $block_type ): bool

Indicates if the matched delimiter is an opening or void delimiter of the given type, if a type is provided, otherwise if it opens any block or implicit freeform HTML content.

Description

This is a helper method to ease handling of code inspecting where blocks start, and for checking if the blocks are of a given type. The function is variadic to allow for checking if the delimiter opens one of many possible block types.

To advance to the start of a block WP_Block_Processor::next_block().

Example:

$processor = new WP_Block_Processor( $html );
while ( $processor->next_delimiter() ) {
    if ( $processor->opens_block( 'core/code', 'syntaxhighlighter/code' ) ) {
        echo "Found code!";
        continue;
    }

    if ( $processor->opens_block( 'core/image' ) ) {
        echo "Found an image!";
        continue;
    }

    if ( $processor->opens_block() ) {
        echo "Found a new block!";
    }
}

See also

Parameters

$block_typestring[]optional
Is the matched block type one of these? If none are provided, will not test block type.

Return

bool Whether the matched block delimiter opens a block, and whether it opens a block of one of the given block types, if provided.

Source

public function opens_block( string ...$block_type ): bool {
	// HTML spans only open implicit freeform content at the top level.
	if ( self::HTML_SPAN === $this->state && 1 !== count( $this->open_blocks_at ) ) {
		return false;
	}

	/*
	 * Because HTML spans are discovered after the next delimiter is found,
	 * the delimiter type when visiting HTML spans refers to the type of the
	 * following delimiter. Therefore the HTML case is handled by checking
	 * the state and depth of the stack of open block.
	 */
	if ( self::CLOSER === $this->type && ! $this->is_html() ) {
		return false;
	}

	if ( count( $block_type ) === 0 ) {
		return true;
	}

	foreach ( $block_type as $block ) {
		if ( $this->is_block_type( $block ) ) {
			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.