wp_restore_image_outer_container()
For themes without theme.json file, make sure to restore the outer div for the aligned image block to avoid breaking styles relying on that div.
Internal function — this function is designed to be used by the kernel itself. It is not recommended to use this function in your code.
No Hooks.
Returns
String. Filtered block content.
Usage
wp_restore_image_outer_container( $block_content, $block );
- $block_content(string) (required)
- Rendered block content.
- $block(array) (required)
- Block object.
Changelog
| Since 6.0.0 | Introduced. |
wp_restore_image_outer_container() wp restore image outer container code WP 6.9.1
function wp_restore_image_outer_container( $block_content, $block ) {
if ( wp_theme_has_theme_json() ) {
return $block_content;
}
$figure_processor = new WP_HTML_Tag_Processor( $block_content );
if (
! $figure_processor->next_tag( 'FIGURE' ) ||
! $figure_processor->has_class( 'wp-block-image' ) ||
! (
$figure_processor->has_class( 'alignleft' ) ||
$figure_processor->has_class( 'aligncenter' ) ||
$figure_processor->has_class( 'alignright' )
)
) {
return $block_content;
}
/*
* The next section of code wraps the existing figure in a new DIV element.
* While doing it, it needs to transfer the layout and the additional CSS
* class names from the original figure upward to the wrapper.
*
* Example:
*
* // From this…
* <!-- wp:image {"className":"hires"} -->
* <figure class="wp-block-image wide hires">…
*
* // To this…
* <div class="wp-block-image hires"><figure class="wide">…
*/
$wrapper_processor = new WP_HTML_Tag_Processor( '<div>' );
$wrapper_processor->next_token();
$wrapper_processor->set_attribute(
'class',
is_string( $block['attrs']['className'] ?? null )
? "wp-block-image {$block['attrs']['className']}"
: 'wp-block-image'
);
// And remove them from the existing content; it has been transferred upward.
$figure_processor->remove_class( 'wp-block-image' );
foreach ( $wrapper_processor->class_list() as $class_name ) {
$figure_processor->remove_class( $class_name );
}
return "{$wrapper_processor->get_updated_html()}{$figure_processor->get_updated_html()}</div>";
}