# 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.

- Type: PHP
- Runs: Frontend only
- Category: [Block Editor](https://wpide.com/library/category/gutenberg/)
- Tags: body-class, css, block-editor
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/body-classes-for-used-blocks/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Body Classes for the Blocks Used on a Page" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
