Blocks::remove_wp_block_classes_and_clean( string $content )
Removes empty HTML elements and elements with classes starting with ‘wp-block-‘ but preserves their inner content, <br> tags, and whitespace.
Contents
phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
Parameters
- $content
-
(string) (Required) The HTML content to process.
Return
(string) The cleaned content.
Source
File: src/Events_Community/Block_Conversion/Blocks.php
public function remove_wp_block_classes_and_clean( string $content ): string {
$dom = new DOMDocument();
libxml_use_internal_errors( true );
$dom->loadHTML( mb_convert_encoding( '<div id="root">' . $content . '</div>', 'HTML-ENTITIES', 'UTF-8' ), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
libxml_clear_errors();
libxml_use_internal_errors( false );
$xpath = new DOMXPath( $dom );
// Query all div elements with a class containing 'wp-block-' or empty divs not containing <br> or significant whitespace.
$nodes = $xpath->query( '//div[contains(concat(" ", normalize-space(@class), " "), " wp-block-") or (not(node()) or normalize-space(.) = "" and not(.//br))]' );
foreach ( $nodes as $node ) {
// Create a document fragment to hold the inner HTML for non-empty elements.
$fragment = $dom->createDocumentFragment();
while ( $node->childNodes->length > 0 ) {
$fragment->appendChild( $node->childNodes->item( 0 ) );
}
// Check if the node should be removed entirely or just have its contents moved up.
if ( $node->hasAttributes() || $node->childNodes->length > 0 ) {
$node->parentNode->replaceChild( $fragment, $node );
} else {
// For truly empty nodes that shouldn't be preserved, remove them without replacement.
$node->parentNode->removeChild( $node );
}
}
// Extract the content from the temporary root div, preserving <br> tags and whitespace.
$root = $dom->getElementById( 'root' );
$new_html = '';
foreach ( $root->childNodes as $child ) {
$new_html .= $dom->saveHTML( $child );
}
return trim( $new_html );
}
Changelog
| Version | Description |
|---|---|
| 4.10.17 | Introduced. |