Skip to content

Commit e801a2a

Browse files
committed
Refactor twentwentyone to use Block_Processor
1 parent 2077aa2 commit e801a2a

File tree

1 file changed

+16
-29
lines changed

1 file changed

+16
-29
lines changed

src/wp-content/themes/twentytwentyone/inc/template-functions.php

Lines changed: 16 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -361,44 +361,31 @@ function twenty_twenty_one_get_non_latin_css( $type = 'front-end' ) {
361361
* @return bool Returns true if a block was located & printed, otherwise false.
362362
*/
363363
function twenty_twenty_one_print_first_instance_of_block( $block_name, $content = null, $instances = 1 ) {
364-
$instances_count = 0;
365364
$blocks_content = '';
366365

367366
if ( ! $content ) {
368367
$content = get_the_content();
369368
}
370369

371-
// Parse blocks in the content.
372-
$blocks = parse_blocks( $content );
370+
$processor = WP_Block_Processor::create( $content );
371+
$visit_freeform = in_array( $block_name, array( 'freeform', 'core/freeform', 'core/*' ), true );
372+
$freeform_flag = $visit_freeform ? 'visit-html' : 'skip-html';
373+
$instance_count = 0;
373374

374-
// Loop blocks.
375-
foreach ( $blocks as $block ) {
375+
if ( str_ends_with( $block_name, '*' ) ) {
376+
// Scan for blocks whose block type matches the prefix.
377+
$prefix = rtrim( $block_name, '*' );
376378

377-
// Confidence check.
378-
if ( ! isset( $block['blockName'] ) ) {
379-
continue;
380-
}
381-
382-
// Check if this the block matches the $block_name.
383-
$is_matching_block = false;
384-
385-
// If the block ends with *, try to match the first portion.
386-
if ( '*' === $block_name[-1] ) {
387-
$is_matching_block = 0 === strpos( $block['blockName'], rtrim( $block_name, '*' ) );
388-
} else {
389-
$is_matching_block = $block_name === $block['blockName'];
379+
while ( $instance_count < $instances && $processor->next_delimiter( $freeform_flag ) ) {
380+
if ( str_starts_with( $processor->get_block_type(), $prefix ) ) {
381+
$blocks_content .= render_block( $processor->extract_block() );
382+
}
390383
}
391-
392-
if ( $is_matching_block ) {
393-
// Increment count.
394-
++$instances_count;
395-
396-
// Add the block HTML.
397-
$blocks_content .= render_block( $block );
398-
399-
// Break the loop if the $instances count was reached.
400-
if ( $instances_count >= $instances ) {
401-
break;
384+
} else {
385+
// Scan for blocks of the exact block type.
386+
while ( $instance_count < $instances && $processor->next_delimiter( $freeform_flag ) ) {
387+
if ( $processor->is_block_type( $block_name ) ) {
388+
$blocks_content .= render_block( $processor->extract_block() );
402389
}
403390
}
404391
}

0 commit comments

Comments
 (0)