Body Classes for the Blocks Used on a Page
Adds body classes such as "has-block-cover" or "has-block-gallery" for the main blocks a post or page contains, so CSS can adapt the header or layout to the content.
Opens WPIDE on
Code
// Blocks to look for.
$wpide_body_class_blocks = array( 'core/cover', 'core/gallery', 'core/table', 'core/video', 'core/embed', 'core/query' );
add_filter( 'body_class', function ( $classes ) use ( $wpide_body_class_blocks ) {
if ( ! is_singular() ) {
return $classes;
}
$post = get_queried_object();
if ( ! $post instanceof WP_Post || ! has_blocks( $post ) ) {
return $classes;
}
foreach ( $wpide_body_class_blocks as $block ) {
if ( has_block( $block, $post ) ) {
$name = 0 === strpos( $block, 'core/' ) ? substr( $block, 5 ) : str_replace( '/', '-', $block );
$classes[] = 'has-block-' . sanitize_html_class( $name );
}
}
return $classes;
} );
Notes
Only the blocks in the list are checked, which keeps it fast. Add any block name you want to style against.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.