Skip to content

Commit 30a3533

Browse files
committed
Block Supports: Use Tag Processor for adding class-name to wrapper
Porting part of WordPress/gutenberg#46625 Replace use of fragile `preg_match` with Tag Processor when adding an element class name to its wrapper.
1 parent dd33e32 commit 30a3533

File tree

1 file changed

+5
-20
lines changed

1 file changed

+5
-20
lines changed

src/wp-includes/block-supports/elements.php

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -56,29 +56,14 @@ function wp_render_elements_support( $block_content, $block ) {
5656
return $block_content;
5757
}
5858

59-
$class_name = wp_get_elements_class_name( $block );
60-
6159
// Like the layout hook this assumes the hook only applies to blocks with a single wrapper.
62-
// Retrieve the opening tag of the first HTML element.
63-
$html_element_matches = array();
64-
preg_match( '/<[^>]+>/', $block_content, $html_element_matches, PREG_OFFSET_CAPTURE );
65-
$first_element = $html_element_matches[0][0];
66-
// If the first HTML element has a class attribute just add the new class
67-
// as we do on layout and duotone.
68-
if ( strpos( $first_element, 'class="' ) !== false ) {
69-
$content = preg_replace(
70-
'/' . preg_quote( 'class="', '/' ) . '/',
71-
'class="' . $class_name . ' ',
72-
$block_content,
73-
1
74-
);
75-
} else {
76-
// If the first HTML element has no class attribute we should inject the attribute before the attribute at the end.
77-
$first_element_offset = $html_element_matches[0][1];
78-
$content = substr_replace( $block_content, ' class="' . $class_name . '"', $first_element_offset + strlen( $first_element ) - 1, 0 );
60+
// Add the class name to the first element, presuming it's the wrapper, if it exists.
61+
$tags = new WP_HTML_Tag_Processor( $block_content );
62+
if ( $tags->next_tag() ) {
63+
$tags->add_class( wp_get_elements_class_name( $block ) );
7964
}
8065

81-
return $content;
66+
return $tags->get_updated_html();
8267
}
8368

8469
/**

0 commit comments

Comments
 (0)