Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fixes markup for <InnerBlocks.Content/> output
<?php
add_filter( 'the_content', function ( $content ) {
// Fix layouts HTML.
libxml_use_internal_errors( true );
$dom = new \DOMDocument( '1.0', 'UTF-8' );
$dom->loadHTML( utf8_decode( $content ) );
$xpath = new \DOMXPath( $dom );
$layout_classes = apply_filters( 'gutenberg_layout_classes', [ 'layout-main', 'layout-sidebar' ] );
foreach ( $layout_classes as $layout ) {
// Get first item with a matching class name inside a div.
$columns = $xpath->query( "//div/*[contains(concat(' ', @class, ' '), ' $layout ')][1]" );
foreach ( $columns as $column ) {
// Get all items with the same layout class within the same div.
$container = $column->parentNode;
$column_items = $xpath->query( "//*[contains(concat(' ', @class, ' '), ' $layout ')]", $container );
// Create a new container element with the layout class name.
$column_node = $dom->createElement( 'div' );
$column_node->setAttribute( 'class', $layout );
// Move all the items with the layout class into the new container.
foreach ( $column_items as $item ) {
// Remove layout class.
$item->setAttribute( 'class', trim( str_replace( $layout, '', (string) $item->getAttribute( 'class' ) ) ) );
$column_node->appendChild( $item );
}
// Append the new container with the now nested layout nodes to the parent.
$container->appendChild( $column_node );
}
}
$content = $dom->saveHTML();
// Remove saveHTML generated output.
$content = fix_content( $content );
libxml_clear_errors();
return $content;
}, 10 );
function fix_content( $html ) {
return trim( preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( array( '<html>', '</html>', '<head>', '</head>', '<body>', '</body>' ), '', $html ) ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.